LESSON 10

Files

Learning objective: Read from and write to files in Python.

Understand

Programs often need to save and load data in files.

Use open() with a mode: 'r' to read, 'w' to write, 'a' to append. The with statement automatically closes the file when done, which is the safe, recommended pattern.

Analogy: Opening a file with with is like borrowing a book and having it returned for you automatically.

See It in Action

Writing and reading:

with open("note.txt", "w") as f:
    f.write("Hello")

with open("note.txt") as f:
    print(f.read())
How it works: The first block writes text to a file; the second opens it for reading and prints the contents.

Try It Yourself

  1. Write a line of text to a file.
  2. Read it back and print it.
  3. Append a second line.

Quick Quiz

Why use the with statement for files?

Challenge

Save a short list of notes to a file and read them back.

Success condition: Your program writes to a file and reads the same content back.