[Tutor] Re: Need to explicitly del a file object after reading contents?

Andrei project5 at redrival.net
Fri Jun 25 12:34:17 EDT 2004


Jeff Kowalczyk wrote on Fri, 25 Jun 2004 10:20:38 -0500:

> I've been explicitly opening, reading, closing and deleting files when I

del does not delete the file. In fact it's not even guaranteed to remove
the file object I think. Even more, if you del a file object which is
currently open, the file will remain open and you won't be able to
overwrite it for example.

> read their contents into variables. In these cases, I don't need
> the file object kept around for anything. I do this mainly because I don't
> know enough about when the garbage collector will delete the file object,
> and I wouldn't want it left open until the gc happens.

That a file object exists, does not mean that the file is open. If you
close the file (which you do in the sample code you provided), the file on
the HD is closed and therefore it's possible to overwrite it, delete it,
open it, whatever you like. This has nothing whatsoever to do with the file
object.

> filestring = open(filepath,'r').read()

In my experience the file is closed immediately if you use this kind of
code, but I don't know if this behavior is guaranteed.

> The same filepath *may* be read or written in the next few seconds/minutes
> by other code, but it usually won't happen. Is there a rule of thumb on
> when to go with the explicit file management? Thanks.

I usually go for the one-liner when reading files.

-- 
Yours,

Andrei

=====
Real contact info (decode with rot13):
cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.




More information about the Tutor mailing list