Anonymous file closing

Peter Hansen peter at
Fri Jun 11 13:06:38 CEST 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')
     text =

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.


More information about the Python-list mailing list