Opening files without closing them

Robert Kern robert.kern at gmail.com
Sun Mar 5 17:44:48 EST 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)?

Both!

Usually, the files will probably be closed *if* you are using CPython. However,
there is absolutely no guarantee of this behavior. For example, Jython uses a
different garbage collection scheme, and the files will *not* close immediately.
Future versions of CPython may have different behavior, too.

> I usually use:
> 
> try:
>   f = open(file)
>   contents = f.read()
> finally:
>   f.close()
> 
> But now I am wondering if that is the same thing. Which method would
> you rather use? Why?

Just keep doing what you are doing, please.

-- 
Robert Kern
robert.kern at gmail.com

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco




More information about the Python-list mailing list