Reading from a file

Note that in the list of file operations in the File I/O section, the standard read modes produce an input/output (I/O) error if the file doesn't exist. If you end up with this error, your program will halt and give you an error message, like in the following screenshot:

File IOError

To fix this, you should always open files in such a way as to catch the error before the program crashes. When you are performing an operation where there is a potential for an exception to occur, you should wrap that operation within a try/except code block. This will attempt to run the operation; if an exception is thrown, you can catch it and deal with it gracefully. Otherwise, your program will error out, potentially causing problems for the user.

Exception handling with files is demonstrated in the following screenshot:

Catching file exceptions

A file is created for writing to in line 69, then we add a string to it and close it (lines 70 and 71, respectively).

A try/except block is written to attempt opening and reading the file in line 72. Because the file exists, it runs as expected and prints the data in the file.

In line 73, we make a new try/except block, this time with a file that doesn't exist. Because it doesn't exist, it would normally print an error message like the previous screenshot. With the exception-catching code, we look explicitly for the IOError, and when it is generated, we print a nice message to the user. Alternatively, we could add code that would provide other functionality, such as automatically looking in a different directory, or presenting the user the option to indicate where the file is located.

One way to open and then automatically close a file, so you don't have to manually close it or wait for the garbage collector, is to use the with keyword when working with file objects. This ensures the file is automatically closed after it is no longer needed, even if an exception arose during processing. The following screenshot provides an example of this:

Auto-closing files

Rather than opening a file like we have in previous examples, line 78 shows how to use the with keyword to open a file and assign it to a variable name. We can process the file like normal, in this case simply printing the file data as before. When we check to see if the file has been closed in line 79, Python tells us that the file is, indeed, closed.