Do open files (and other resources) get automatically closed when the script exits due to an exception?
I\'m wondering if I need to be closing my resources during my
No, they don't.
Use with
statement if you want your files to be closed even if an exception occurs.
From the docs:
The
with
statement is used to wrap the execution of a block with methods defined by a context manager. This allows common try...except...finally usage patterns to be encapsulated for convenient reuse.
From docs:
The with
statement allows objects like files to be used in a way that ensures they are always cleaned up promptly and correctly.
with open("myfile.txt") as f:
for line in f:
print line,
After the statement is executed, the file f
is always closed, even if a problem was encountered while processing the lines. Other objects which provide predefined clean-up actions will indicate this in their documentation.