Skip to main content

Section 10.7 Advanced Topic: with Statements

Note 10.7.1.

This section is a bit of an advanced topic and can be easily skipped. But with statements are becoming very common, and it doesn’t hurt to know about them in case you run into one in the wild.
Now that you have seen and practiced a bit with opening and closing files, there is another mechanism that Python provides for us that cleans up the often forgotten close. Forgetting to close a file does not necessarily cause a runtime error in the kinds of programs you typically write in an introductory CS course. It will rarely, if ever, cause a problem if you forget to close an input file. However, if you forget to close an output file, there is a possibility that some of your data will not get written to the file.
In version 2.5, Python introduced the concept of a context manager. A context manager automates the process of doing common operations at the start of some task, as well as automating certain operations at the end of the task. In the context of reading and writing a file, the normal operation is to open the file and assign it to a variable. At the end of working with a file, the common operation is to make sure that file is closed.
Here is an concrete example of a with statement that helps us manage the context of opening and closing files. Here’s our daily temperature file again:
Data: daily_weather.txt
2022-06-01,12,29
2022-06-02,13,25
2022-06-03,14,24
2022-06-04,15,24
2022-06-05,17,27
2022-06-06,14,25
2022-06-07,13,26
2022-06-08,14,26
2022-06-09,13,33
2022-06-10,17,36
2022-06-11,18,33
2022-06-12,15,27
2022-06-13,13,24
2022-06-14,14,30
2022-06-15,14,28
2022-06-16,12,23
2022-06-17,13,22
2022-06-18,11,23
2022-06-19,11,29
2022-06-20,13,31
2022-06-21,16,39
2022-06-22,21,36
2022-06-23,18,32
2022-06-24,17,31
2022-06-25,14,28
2022-06-26,15,27
2022-06-27,15,28
2022-06-28,14,28
2022-06-29,13,23
2022-06-30,14,23
The first line of the with statement opens the file and assigns it to input_file. We can iterate over the file in any of the usual ways. When we are done, we stop indenting and let Python take care of closing the file and cleaning up.