Use a Python with statement to work with a file, and show that the file is closed afterwards.
The with statement runs a block of code and guarantees that the resource is released when the block ends, whether the block ended normally or because of an exception.
# Write a small file in the current folder.
with open('hello.txt', 'w', encoding='utf-8') as handle:
handle.write('hello with\n')
# The file is already closed, even though we left the block.
print('closed:', handle.closed)
# Read it back to show that the content was saved.
with open('hello.txt', 'r', encoding='utf-8') as handle:
print(handle.read().strip())
The line that prints closed: is the whole point of this construct. After the with block, the closed attribute of the file object is True, and that is still true when an exception was raised inside the block. The file is closed in that case too, and the exception still travels up to the code that called the function.
Behind the syntax, the file object is a context manager. It implements __enter__, which returns the resource that gets attached to the target name, and __exit__, which runs when the block finishes. The with statement is really only a tidier way of writing a try and finally pair.
You can also write your own context managers, and the class-based form is worth recognising.
class Managed:
def __enter__(self):
print('enter')
return self
def __exit__(self, exc_type, exc, tb):
print('exit')
return False # do not hide the exception
with Managed():
print('body')
The output is enter, then body, then exit. The value that __exit__ returns decides what happens to an exception. Returning False, or None, lets the exception continue on its way, while returning True hides it.