LearnPy Hub
IntermediateIntermediateLesson 17 of 32

File Handling

Watch the ideaWriting and reading a file
with open("notes.txt", "w") as f:
notes.txt
(empty)

Mode 'w' creates the file, or empties it if it already exists.

1Level 1 · BasicsBasics

Variables disappear when a program ends. To keep data, such as scores, notes or settings, programs save it in files. Python makes reading and writing files short and safe.

Opening a file with with

with open("notes.txt", "w") as f:
    f.write("Hello file!\n")

open() takes the file name and a mode. The with block automatically closes the file at the end, even if an error happens. Always use with.

ModeMeaning
"r"read (the default); the file must exist
"w"write; erases the file first, or creates it
"a"append; adds to the end of the file

Writing

f.write(text) writes text exactly as given. It does not add a new line, so include "\n" yourself. Only strings can be written, so convert numbers with str() or an f-string.

Reading

with open("notes.txt") as f:
    text = f.read()          # the whole file as one string

with open("notes.txt") as f:
    for line in f:           # one line at a time
        print(line.strip())  # strip() removes the "\n"

f.readlines() gives a list of lines. Looping line by line is the most memory-friendly way to read big files.

CSV files

CSV (comma-separated values) is the simplest spreadsheet format. The csv module reads and writes it safely, including values that contain commas. Later, pandas reads a CSV into a table in one line.

Files that may not exist

Opening a missing file for reading raises FileNotFoundError. Catch it with try/except, or check first with os.path.exists("data.txt").

Key points: use with open(name, mode) as f:; "w" overwrites, "a" appends, "r" reads; write strings and add "\n" yourself; loop over the file to read lines; use the csv module for CSV data.

See it in actionWriting, then reading a file

The first with block writes two lines; the second reads them back as a list.

Step-by-step

Try it yourselfExample 1: Write, then read back

The examples run in your browser, so these files live in a small temporary file system there.

example_1.py
Output appears here
Fill in the blanks

Write then read

Fill the blanks so the program writes Hello file to notes.txt and reads it back.

blanks.py
with open("notes.txt", "") as f:
    f.write("Hello file")
with open("notes.txt", "") as f:
    print(f.read())
Fix the bug

Writing to a read-only file

This should save Score: 90 and print it back, but it crashes. Fix the first open.

buggy.py

Example 2: Append and read line by line

Mode "a" adds to the end instead of erasing.

example_2.py
Output appears here
Fill in the blanks

Count the lines

Fill the blanks so the program appends a line and then counts the lines: 3.

blanks.py
with open("log.txt", "w") as f:
    f.write("one\ntwo\n")
with open("log.txt", "") as f:
    f.write("three\n")
with open("log.txt") as f:
    print(len(f.()))

Example 3: CSV with the csv module

csv.writer writes rows; csv.DictReader reads each row as a dictionary.

example_3.py
Output appears here
Your turn

Total from a file

The starter writes prices to prices.txt, one per line. Read the file and print the total: Total: 75.

my_code.py

Example 4: Handling a missing file

Catch FileNotFoundError instead of crashing.

example_4.py
Output appears here
Your turn

A file that isn't there

Try to open missing.txt. If it doesn't exist, print No such file instead of crashing.

my_code.py

2Level 2 · IntermediateCSV with headers, JSON and paths

csv.DictReader and DictWriter

With a header row, csv.DictReader gives each row as a dictionary (row["marks"]) so you don't need to remember column numbers. Always open CSV files with newline="".

JSON files

json.dump(data, f, indent=2) saves lists and dictionaries as readable text; json.load(f) reads them back. Perfect for saving a game or settings.

pathlib

Path("data") / "marks.csv" builds paths that work on every operating system. p.exists(), p.read_text(), p.write_text() and Path(".").glob("*.csv") cover most needs.

Encodings

Pass encoding="utf-8" when reading or writing text, especially Bangla, so the file reads the same on every computer.

Example 5: DictWriter, then DictReader

Columns are accessed by name, so their order in the file doesn't matter.

example_5.py
Output appears here

Example 6: Save and load with JSON and pathlib

Run it twice in your head - the second load sees the saved high score.

example_6.py
Output appears here

3Level 3 · AdvancedBig files, safe writes and binary data

Stream, don't slurp

f.read() loads the whole file into memory. For big files, loop for line in f:, which reads one line at a time, or read fixed-size chunks with f.read(4096).

Safe writes

If a program crashes halfway through writing, the file is left broken. Write to a temporary file first, then os.replace(tmp, real) swaps it in one step.

Binary mode

"rb" and "wb" work with bytes (images, zip files). f.seek() and f.tell() move around inside a file.

Files in memory

io.StringIO behaves like a text file without touching the disk, which is handy for tests and for reading CSV text you already have.

Example 7: Streaming a large log file

Only one line is in memory at a time, however big the file is.

example_7.py
Output appears here

Example 8: Safe save, binary bytes and StringIO

os.replace swaps the finished file in one step.

example_8.py
Output appears here
CarefulMode "w" erases the file the moment it's opened, even before you write anything. To add to an existing file, use "a".
Exercise · predict the output

What does this print?

with open("t.txt", "w") as f:
    f.write("ab")
    f.write("cd")
with open("t.txt") as f:
    print(f.read())
Quick quiz · 5 questions
1. Why use with open(...) as f?
2. Which mode adds to the end of a file without erasing it?
3. What does f.write("hi") write?
4. Which exception happens when you read a file that doesn't exist?
5. What does line.strip() remove from a line read from a file?
Ready to practice file handling?

50 graded problems are waiting in Topic Practice.

Practice this topic →
Python File Handling · LearnPy Hub