In Python, if you either open a file without calling close()
, or close the file but not using try
-finally
or the "with
" statement, is this a problem? Or does it suffice as a coding practice to rely on the Python garbage-collection to close all files? For example, if one does this:
for line in open("filename"):
# ... do stuff ...
... is this a problem because the file can never be closed and an exception could occur that prevents it from being closed? Or will it definitely be closed at the conclusion of the for
statement because the file goes out of scope?
for
block. Its reference count will go to zero, causing it to be closed automatically, but only functions, classes, and modules define scopes in Python, not other compound statements. – Grendelfor
blocks and functions/classes/modules. It's much simpler than that: objects don't have scopes, only names do. There is no name that refers to this object, so there is nothing here to stay in scope or go out of scope. – Androgenfor
loop, and mentioning that the file gets closed for an entirely different reason. It doesn't get into what scopes are in Python, as it's not relevant here. – Grendel