Questions about file object and close()

Peter Hansen peter at engcorp.com
Thu Dec 9 08:41:54 EST 2004


John Marshall wrote:
> Hi,
> 
> Does anyone see a problem with doing:
>     data = file("tata").read()
> 
> Each time this is done, I see a new file
> descriptor allocated (Linux) but not
> released.
> 
> 1) Will there ever be a point where I
>    will have a problem with file
>    descriptors because the garbage
>    collector has _not_ yet collected the
>    file objects?

Should be easy to check.  Write a loop which
does that many times.  There are a finite
number of file descriptors available, so if
it's going to fail, it will fail fairly
quickly.

> 3) There is no file.__del__() as far as I
>    can tell at the Python level. Are files
>    opened by the calls above properly
>    closed when the objects are destroyed
>    and collected?

Yes, but you can only count on this happening
in the CPython implementation.  Nevertheless,
it's still widely considered more than just good style
to explicitly close your files within a finally
clause, even in CPython where technically you don't
have to in most cases:

f = file("tata")
try:
     data = f.read()
finally:
     f.close()

The above is quite robust and should be your model
for all file access, at least until you're much more
experienced with Python.

One should use the open().read() idiom only in small
utility scripts and other such short-running applications.

-Peter



More information about the Python-list mailing list