open.read

François Pinard pinard at iro.umontreal.ca
Thu Aug 21 07:49:04 EDT 2003


[Alex Martelli]
> David Bear wrote:

> > I was in a hurry to do something and I did
> >    stuff = open("filename", "r").read()
> > then I realized, "hey I didn't close the file".
> > so python close it automagically?

> It's very common use in classic Python, and sometimes handy for
> interactive or near-one-liner use, but in any "serious" program explicitly
> closing the file just as soon as you're done with it is beter than relying
> on the interpreter closing it for you

In more recent versions of Python, the `open' built in function has been
replaced by the `file' built in constructor, and `open' has been made an
alias for `file', so the above may more adequately be written:

    stuff = file("filename", "r").read()

The file object created by the `file' constructor has its own destructor,
which closes the file automatically if not done already.  Using `file' is
Pythonesque.  For simple usages like the one above, you can safely rely on
Python for destroying the file object, even in extra-serious programs :-).
"Better" is a question of opinion, but in the case here, it seems to me that
cluttering your code with an assignment, only meant for an explicit close,
does not buy you legibility, and moreover, your assignment will get your
closed file object uselessly hanging around.  Best is exactly what you did.
(I would have not used the `, "r"' part in this case.)

> it will make your code more usable in Jython,

This is likely the only real advantage of cluttering your code, when you
know or bet that you are going to use Jython one of these days.

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard





More information about the Python-list mailing list