Is a with on open always necessary?

A

Andrea Crotti

I normally didn't bother too much when reading from files, and for example
I always did a

content = open(filename).readlines()

But now I have the doubt that it's not a good idea, does the file
handler stays
open until the interpreter quits?

So maybe doing a

with open(filename) as f:
contents = f.readlines()

is always a better idea??
 
S

Steven D'Aprano

I normally didn't bother too much when reading from files, and for
example I always did a

content = open(filename).readlines()

But now I have the doubt that it's not a good idea, does the file
handler stays open until the interpreter quits?

The file will stay open until:

1) you explicitly close it;
2) the reference to the open file goes out of scope and is garbage
collected; or
3) the Python environment shuts down

whichever happens first.

In the case of #2, the timing is a matter of implementation detail.
CPython and PyPy currently close the file immediately the last reference
to it goes out of scope (but that's not a promise of the language, so it
could change in the future); Jython and IronPython will eventually close
the file, but it may take a long time.

Except for the quickest and dirtiest scripts, I recommend always using
either the "with file as" idiom, or explicitly closing the file.
 
K

K Richard Pixley

I normally didn't bother too much when reading from files, and for example
I always did a

content = open(filename).readlines()

But now I have the doubt that it's not a good idea, does the file
handler stays
open until the interpreter quits?

So maybe doing a

with open(filename) as f:
contents = f.readlines()

is always a better idea??

It's a better idea when possible.

Sometimes the descriptor is opened in one method and closed in another.
In that case, "with" isn't possible.

--rich
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,165
Latest member
JavierBrak
Top