abalter
abalter

Reputation: 10383

Is file automatically closed if read in same line as opening?

If I do (in Python):

text = open("filename").read()

is the file automatically closed?

Upvotes: 4

Views: 71

Answers (3)

kindall
kindall

Reputation: 184091

In CPython (the reference Python implementation) the file will be automatically closed. CPython destroys objects as soon as they have no references, which happens at the end of the statement at the very latest.

In other Python implementations this may not happen right away since they may rely on the memory management of an underlying virtual machine, or use some other memory management strategy entirely (see PyParallel for an interesting example).

Python, the language, does not specify any particular form of memory management, so you can't rely on the file being closed in the general case. Use the with statement to explicitly specify when it will be closed if you need to rely on it.

In practice, I often use this approach in short-lived scripts where it doesn't really matter when the file gets closed.

Upvotes: 3

wim
wim

Reputation: 362517

Since you have no reference on the open file handle, CPython will close it automatically either during garbage collection or at program exit. The problem here is that you don't have any guarantees about when that will occur, which is why the with open(...) construct is preferred.

Upvotes: 2

Jean-François Fabre
Jean-François Fabre

Reputation: 140148

The garbage collector would be activated at some point, but you cannot be certain of when unless you force it.

The best way to ensure that the file is closed when you go out of scope just do this:

with open("filename") as f: text = f.read()

also one-liner but safer.

Upvotes: 6

Related Questions