If I do (in Python):
text = open("filename").read() is the file automatically closed?
If I do (in Python):
text = open("filename").read() is the file automatically closed?
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.
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.