[Tutor] file enigma
Tim Golden
mail at timgolden.me.uk
Thu Jun 11 11:21:31 CEST 2009
spir wrote:
> Hello,
>
> text = file(filename).read()
>
> (or: open(filename).read())
>
> How do you close() the file? ;-)
Well, in any version of Python, you can do this:
<code>
f = open (filename)
text = f.read ()
f.close ()
</code>
or, slightly more robsustly:
<code>
f = open (filename)
try:
text = f.read ()
finally:
f.close ()
</code>
But in Python 2.5+ that can be spelt:
<code>
with open (filename) as f:
text = f.read ()
</code>
As it happens, in CPython at the moment, the file object will
be closed when all references are released -- which would be
at the end of the line in your example. I don't know whether
that's guaranteed by the implementation, or merely the case
at present. It's certainly *not* the case in other implementations,
such as IronPython & Jython which don't use the same kind of
refcounting.
FWIW, in non-critical code I often use the style you illustrate
above: text = open (filename).read (). But in production code,
I usually use the with statement.
TJG
More information about the Tutor
mailing list