Opening files without closing them

Steven Bethard steven.bethard at
Mon Mar 6 01:36:47 CET 2006

Sandra-24 wrote:
> I was reading over some python code recently, and I saw something like
> this:
> contents = open(file).read()
> And of course you can also do:
> open(file, "w").write(obj)
> Why do they no close the files? Is this sloppy programming or is the
> file automatically closed when the reference is destroyed (after this
> line)? I usually use:
> try:
>   f = open(file)
>   contents =
> finally:
>   f.close()
> But now I am wondering if that is the same thing. Which method would
> you rather use? Why?

In Python 2.5, you'll write::

     with open(file) as f:
         contents =

and Python will automatically close the file at the end of the 
with-statement.  Observe:

Python 2.5a0 (trunk:42857M, Mar  5 2006, 14:50:28) [MSC v.1310 32 bit 
(Intel)] on win32
 >>> from __future__ import with_statement
 >>> with open('readme.txt') as f:
...     contents =
 >>> f
<closed file 'readme.txt', mode 'r' at 0x00B8BAA8>

Of course, you have to wait until August or so for Python 2.5:


More information about the Python-list mailing list