Chapter 11

Files and Exception Handling

A program becomes far more useful once it can keep information after it stops, and recover from the problems you can see coming.

Chapter 11, Files and Exception Handling

What you will learn

  • Read and write text files safely.
  • Understand common file modes.
  • Use with open(...) so files close reliably.
  • Catch specific exceptions without hiding programming mistakes.

The code from this chapter

Type these programs yourself. The predictions below are the exercises; the explanations are in the book.

11.1 Writing a Text File

TPRM Lab 11.1: Write and Read

Type this into a file, predict the output, then run it.

Python
with open("notes.txt", "w", encoding="utf-8") as file:
    file.write("First note\n")
    file.write("Second note\n")

with open("notes.txt", "r", encoding="utf-8") as file:
    contents = file.read()

print(contents)

11.2 Expected Errors

TPRM Lab 11.2: Handle Numeric Input

Type this into a file, predict the output, then run it.

Python
while True:
    try:
        age = int(input("Age: "))
        break
    except ValueError:
        print("Please enter a whole number.")

print("Recorded age:", age)

Back to Python the TPRM Way