4

If I do (in Python):

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

is the file automatically closed?

1
  • open would return a filehandle. since you never capture that handle, even if the file stays open, you'd have nothing to read from. Commented Sep 16, 2016 at 19:25

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

4 Comments

Are you sure about the "at the end of the statement" part? And if so, how, may I ask?
CPython frees objects when their reference count reaches zero. This isn't done explicitly at the end of a statement (that was an oversimplification and I have revised my answer slightly). read() on a file holds a reference to the file, but as soon as that returns, there are no references to the file, so it goes away. I am sure about that because CPython is documented as using reference counting (with supplemental garbage collection for cleaning up reference cycles) and that's how reference counting works.
I know how reference counting works, but my experience with the garbage collector is that it is impossible to predict when it will get called (unless you do it yourself, of course). So I take exception to your claim.
The garbage collector is only used to resolve cyclic references. It isn't involved in this situation.
2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.