Opening files without closing them
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Sun Mar 5 21:03:06 EST 2006
Sandra-24 a écrit :
> 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)?
IIRC, the current CPython implementation takes care of closing file
objects that are no longer referenced. But this may not be true of other
implementations (think: Jython).
> I usually use:
>
> try:
> f = open(file)
> contents = f.read()
> finally:
> f.close()
>
> But now I am wondering if that is the same thing.
Not quite:
>>> try:
... f = open('file_that_doesnt_exists.ext')
... finally:
... f.close()
...
Traceback (most recent call last):
File "<stdin>", line 4, in ?
NameError: name 'f' is not defined
>>>
> Which method would
> you rather use?
For a quick script, the simplest one. For production code, it depends
too much on the context to give a definitive single answer.
More information about the Python-list
mailing list