Closing files

Jerry Sievers jerry at jerrysievers.com
Sun Nov 28 20:58:04 EST 2004


news+0409 at henrikholm.com (Henrik Holm) writes:

[+]
> 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()

Verbose and readable.  A typical approach.

[+]
> 
> 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?

It appears to be closed on my Linux system as by using this shorthand
approach, you are not saving any reference to the file object.

Evidently, it is closed immediatly after the statement executes.
There's no point in the file staying open as you'd have no way to
refer to it any more.

[+]
> 
> Similarly, for reading the output from other programs or system
> commands, I would do:
> 
>   o = popen('executable')
>   lines = o.readlines()
>   o.close()
> 
> Is it OK to do this with a one-liner as well, with
> 
>   lines = popen('executable').readlines()

My guess is that this is probably OK too.  At least for simple cases.

My experience has been, that by going for maximum terseness, you
eventually get into trouble somehow.

YMMV

[+]
> 
> without closing the file object?

If you are going to have one or more references to the file or pipe
object, you must either close them or delete the reference to the
object using del().

If you are running on Unix, do some experimentation with the 'fuser'
or 'lsof' commands to see if the system is reporting the files open or
closed.

Or why not for fun;

while True:
	file('/tmp/foo')

I bet this runs forever and you don't run out of open file descriptors
:-)


[+]
> 
> Thanks,
> Henrik Holm

-- 
-------------------------------------------------------------------------------
Jerry Sievers   305 854-3001 (home)     WWW ECommerce Consultant
                305 321-1144 (mobile	http://www.JerrySievers.com/



More information about the Python-list mailing list