Manual file closure, as well as leaving the closing responsibility to the execution environment, have one significant drawback. If an error occurs between opening a file for writing and closing it:
- In the best-case scenario, the file will remain open for too long, but a reference may still exist
- In the worst case, we may lose some data
It is desirable to automatically close the file immediately after finishing work with it, and even in case of an error. File objects can already work in this mode, but we should use them as context managers.
What are context managers
A context manager is an object that implements the corresponding protocol (yes, protocols everywhere!). Objects that implement this protocol allow the use of the following special syntax:
with object as foo:
# We have access to the resource `foo`
# This is the body of the block
# The `foo` resource has already been released, even if there is an error in the body
All the code inside the with
block works within the context. The context often involves acquiring a specific resource, such as a file. When we exit the context, the resource is automatically released, even if an exception occurred while executing the block. It is what we need.
How to use files as context managers
Let us consider a comprehensive example. We will rewrite the script for numbering the lines of a file from the previous lesson:
with open("input.txt", "r") as input_file:
with open("output.txt", "w") as output_file:
for i, line in enumerate(input_file, 1):
output_file.write(
f"{i}) {line}"
)
Explicit calls to close
are gone, but now the files are closed reliably and on time.
Later, we will look at the context manager protocol and explore some of its built-in implementations. However, the file context manager is the most commonly used in everyday Python programming. Learn to use it, and your programs will be more robust!
Are there any more questions? Ask them in the Discussion section.
The Hexlet support team or other students will answer you.
For full access to the course you need a professional subscription.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.