when should I explicitely close a file?

Dave Angel davea at ieee.org
Wed Apr 14 04:09:50 CEST 2010


gelonida 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).
>
>
> Thanks for explaining me exactly what kind of evil I could encounter
> with not explicitely closing.
>
>
>   
Evil?  No.  Just undefined behavior.

The language does NOT guarantee that a close or even a flush will occur 
when an object "goes out of scope."  This is the same in Python as it is 
in Java.  There's also no exception for data not being flushed.

In one particular implementation of Python, called CPython, there are 
some things that tend to help.  So if you're sure you're always going to 
be using this particular implementation, and understand what the 
restrictions are, then go ahead and be sloppy.  Similarly, on some OS 
systems, files are flushed when a process ends.  So if you know your 
application is only going to run on those environments, you might not 
bother closing files at the end of execution.

It all depends on how restrictive your execution environment is going to be.

DaveA




More information about the Python-list mailing list