Skip to main content

Section 11.3 With Statements

In order to open files easily in Python, we can use the following form:
with <some open statement> as <variable name for the file>:
    do some stuff with the file
    ...
When the program exits the with block, the file is automatically closed. Consider the following example:
The first line of the with statement opens the file and assigns it to myfile, then we can iterate over each line in the file. When we are done, we simply stop indenting and let Python take care of closing the file and cleaning up.

Note 11.3.1.

A word of caution: once you read all the lines from a file, it is "spent"; that is to say, if we tried to read from myfile again in the example above, it would not work. We would have to open the file again to read again.
In this course, you likely will not see the following syntax, but it’s still useful to know that it’s out there:
In Python, we can call the open function to open files before we can use them and the close function to close them when we are done with them. As you might expect, once a file is opened it becomes a Python object just like all other data. Table 11.3.2 shows the functions and methods that can be used to open and close files.
Table 11.3.2.
Method Name Use Explanation
open open(filename,'r') Open a file called filename and use it for reading. This will return a reference to a file object.
open open(filename,'w') Open a file called filename and use it for writing. This will also return a reference to a file object.
close filevariable.close() File use is complete.
You have attempted 1 of 2 activities on this page.