when should I explicitely close a file?

Chris Rebert clp2 at rebertia.com
Tue Apr 13 18:24:34 EDT 2010


On Tue, Apr 13, 2010 at 3:01 PM, gelonida <gelonida at gmail.com> wrote:
> Hi,
>
> I've been told, that following code snippet is not good.
>
> open("myfile","w").write(astring) , because I'm neither explicitely
> closing nor using the new 'with' syntax.
>
> What exactly is the impact of not closing the file explicitely
> (implicitley with a 'with' block)?
>
> Even with my example
> I'd expected to get an exception raised if not all data could have
> been written.
>
> I'd also expected, that all write data is flushed as soon as the
> filehandle is out of scope (meaning in the next line of my source
> code).

That extremely-quick responsiveness of the garbage-collection
machinery is only guaranteed by CPython, not the language
specification itself, and indeed some of the other implementations
*explicitly don't* make that guarantee (and hence the data may not get
flushed in a timely manner on those implementations). And portability
of code is encouraged, hence the admonishment you encountered.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list