1. Concept library
  2. Python Foundations
  3. Module 7: Files and exceptions

Concept

Reading and writing files

open() gives a file object you can read line by line or write to. The mode decides whether you read, overwrite or append, and files should always be closed when you are done.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain what the modes r, w and a do to a file when it opens
  2. Write code that reads a file line by line and writes a result to another
  3. Spot why opening with "w" lost the old content, and append instead

In practice

A few lines that show Reading and writing files doing its job.

Python
with open("notes.txt", "w") as f:
    f.write("first line\n")

with open("notes.txt", "a") as f:
    f.write("second line\n")

with open("notes.txt") as f:
    for line in f:
        print(line.rstrip())

The common mistake

Watch for

Opening with "w" to add to a file. Write mode truncates the file the moment it opens, so the old content is gone. Append with "a".

What to know first

Your roadmap puts these before Reading and writing files, unless you already know them.

How it stays learned

Once a session shows you understand Reading and writing files, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled

Where it leads

Topics that build on Reading and writing files.

Next in the moduletry and except →