Introduction
The very basics of text files
with statement and exception handling
10. Exceptions and IOError
Summary

Instruction

Good. As you could see, when we work with text files, it's possible that things can go wrong. For example, a file we're trying to open on the user's computer may not exist, or it may contain a letter when we expect a number. Such situations are called exceptions (exceptional, or unexpected, circumstances).

By default, Python will show its own kind of error message and stop the program when it encounters an exception, as you could see in the experiment. We can change that behavior using try-except blocks, which allow our code to handle the exception. Take a look:

try:
  with open('misssing_file.txt', 'r') as file:
    print(file.read())
except IOError:
  print('Could not read the file.')

In the code above, we try to execute the code in the try block. The code opens the file and prints its contents to the console. We know this code may fail. Specifically speaking, we expect that an IOError may occur. IO stands for Input-Output. An Input-Output error is one related to handling files – such as a full disk or nonexistent file – and other user input errors. If an IO error is thrown by the application, the execution of the try block is interrupted, and Python moves on to the except-block. In this case, we print our custom error message:

Could not read the file.

When we handle an exception in the expect block, the program execution is not interrupted – any further code can be still executed.

Python comes with many kinds of built-in error types, and IOError is just one of them.

Exercise

Ask the user for a text file name. If the file exists, print:

Read the file successfully!

After a line break, print the contents of the file. If the file does not exist, print:

The file does not exist!

Stuck? Here's a hint!

Get the file name with the input() function.