Python Foundations · Lesson 11 of 12

Working with text files

Writing, reading and with-open blocks. Learn through short examples, practical tasks and targeted questions.

← All lessons

Reading and writing text files

Text files let a program retain simple data between runs. Opening a file with with closes it automatically at the end of the block. Try writing a few lines, reading them back and checking whether extra newline characters affect the output.

Watch out: Opening a file in write mode replaces its previous contents. Use append mode when earlier lines must be preserved.

1 · Understand

Writing, reading and with-open blocks. Study the code and predict what it does before running it. Change a value or string and observe how the output changes.

with open("notes.txt", "w", encoding="utf-8") as file:
    file.write("Revise loops\n")
with open("notes.txt", "r", encoding="utf-8") as file:
    print(file.read())
Download example .py ↓

2 · Practise

Create a program that writes three revision targets to a local text file, then reads and prints them.

Plan your inputs, processing and outputs. Write the code in Mu, IDLE or PyCharm; test at least three cases.

Show a reference solution after attempting the task
targets = ["Practise loops", "Revise lists", "Test functions"]
with open("targets.txt", "w", encoding="utf-8") as file:
    for target in targets:
        file.write(target + "\n")
with open("targets.txt", "r", encoding="utf-8") as file:
    print(file.read())
Download reference solution .py ↓

3 · Debug the code

Identify the problem and explain how to fix it before revealing the answer.

with open("notes.txt", "r") as f:
    f.write("Hi")
Reveal the corrected program and explanation
with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("Hi")

Compare the two snippets. Identify the changed line, run the corrected version and explain the effect.

4 · Check your understanding

Which file mode overwrites a text file when opened?

5 · Challenge and reflect

Extension: Improve your solution to deal with unexpected input, add a second feature or display results more clearly.

Reflect: What was the hardest part? What would you test if someone else used your program?

Want extra practice? Try interactive Python tracing and debugging questions →

APPLY THE IDEA

Use this skill beyond the example

Test file code using a known small file before trying larger datasets. Explain why with open(...) is usually safer than leaving a file open, and handle the possibility that the requested file is missing.

Quick check: What happens when opening a missing file for reading without handling errors?

Check: Python raises FileNotFoundError.