Anonymous file closing

Peter Hansen peter at engcorp.com
Fri Jun 11 07:06:38 EDT 2004


Sergey Krushinsky wrote:

> If I need to read a string from a file and use syntax like:
> text = open(filename, 'r').read()
> ...
> is the file object ever closed?

Duncan's response says it all, but here's the solution
if you don't like the uncertainty inherent in the above:

f = open(filename, 'r')
try:
     text = f.read()
finally:
     f.close()

That will ensure that the file is properly closed under
all versions of Python, all platforms...

For small scripts, I do what you did above.  For anything
larger I take the more explicit approach.

-Peter



More information about the Python-list mailing list