Closing files

Daniel Dittmar daniel.dittmar at sap.corp
Mon Nov 29 09:02:05 EST 2004


Henrik Holm wrote:
> I have recently started playing around with Python.  Some of the things
> I have done have involved reading files.  The way I do this is along the
> lines of
> 
>   f = file('file.txt')
>   lines = f.readlines()
>   f.close()
> 
> I have noticed that it is possible to do this in one line:
> 
>   lines = file('file.txt').readlines()
> 
> My question is: does the file get closed if I do the reading in this
> manner?

The file gets closed in CPython because file objects are closed when the 
last reference to them gets deleted. (I guess when the .readlines () 
returns)

When you use Jython or IronPython, the file will be closed sometime 
later when the file object gets garbage collected. This can lead to 
problems becaause the process might run out of file handles before the 
garbage collection and file locks are held a lot longer.

This led to two camps.

One camp thinks that the correct way would be
f = file('file.txt')
try:
     lines = f.readlines()
finally:
     f.close()

The other camp thinks that reference counting should be implemented in 
all Python implementations.

And then there are a lot of people who think that changing all the 
readlines one liner would be quite easy should the need of a Jython port 
arrive, so why bother about it now?

Daniel



More information about the Python-list mailing list