My first Python program

Chris Torek nospam at torek.net
Wed Oct 13 14:27:55 EDT 2010


In article <mailman.1673.1286992432.29448.python-list at python.org>
Jonas H. <jonas at lophus.org> wrote:
>On 10/13/2010 06:48 PM, Seebs wrote:
>> Is it safe for me to assume that all my files will have been flushed and
>> closed?  I'd normally assume this, but I seem to recall that not every
>> language makes those guarantees.
>
>Not really. Files will be closed when the garbage collector collects the 
>file object, but you can't be sure the GC will run within the next N 
>seconds/instructions or something like that. So you should *always* make 
>sure to close files after using them. That's what context managers were 
>introduced for.
>
>     with open('foobar') as fileobject:
>         do_something_with(fileobject)
>
>basically is equivalent to (simplified!)
>
>     fileobject = open('foobar')
>     try:
>         do_something_with(fileobject)
>     finally:
>         fileobject.close()
>
>So you can sure `fileobject.close()` is called in *any* case.

Unfortunately "with" is newish and this code currently has to
support python 2.3 (if not even older versions).
-- 
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W)  +1 801 277 2603
email: gmail (figure it out)      http://web.torek.net/torek/index.html



More information about the Python-list mailing list