Aral Code

Functions & Modules Lesson 20 of 23

Python File Handling — Read and Write Text Files

Save and load data with text files — open() modes, with statements, reading lines, writing and appending, and working with CSV files of grades.

Variables disappear when your program ends. To keep data, like a class list, high scores or a store's inventory, save it in a file. Python makes reading and writing text files simple.

Writing a file

with open("students.txt", "w") as f:
    f.write("Ana\n")
    f.write("Ben\n")
    f.write("Carla\n")
print("Saved!")

Output

Saved!

This creates students.txt in the same folder as your program. Let's break it down:

  • open("students.txt", "w") opens the file for writing.
  • with ... as f: gives the open file the name f and closes it automatically when the block ends.
  • f.write() writes text. It doesn't add new lines by itself, so we add \n.

File modes

ModeMeaning
"r"Read (default). Error if the file doesn't exist.
"w"Write. Creates the file, or erases it if it exists.
"a"Append. Adds to the end without erasing.

Reading a file

with open("students.txt", "r") as f:
    content = f.read()
print(content)

Output

Ana
Ben
Carla

Reading line by line

with open("students.txt") as f:
    for i, line in enumerate(f, start=1):
        print(i, line.strip())

Output

1 Ana
2 Ben
3 Carla

Each line includes its \n at the end, so .strip() removes it. You can also get all lines as a list with f.readlines(), or f.read().splitlines() for a list without the \n.

Appending

from datetime import date

with open("attendance.txt", "a") as f:
    f.write(f"{date.today()} - Ana - present\n")

Run it several times, and the file grows by one line each time.

Saving a list and loading it back

grades = [88, 92, 79, 95]

# Save, one grade per line
with open("grades.txt", "w") as f:
    for g in grades:
        f.write(f"{g}\n")

# Load
loaded = []
with open("grades.txt") as f:
    for line in f:
        loaded.append(int(line))

print(loaded, sum(loaded) / len(loaded))

Output

[88, 92, 79, 95] 88.5

Files store only text, so numbers must be converted back with int() or float() after reading.

CSV files

A CSV (comma-separated values) file is a simple table that Excel and Google Sheets can open. Python's csv module handles it:

import csv

rows = [
    ["Name", "Math", "Science"],
    ["Ana", 88, 91],
    ["Ben", 76, 82],
    ["Carla", 95, 93],
]
with open("grades.csv", "w", newline="") as f:
    csv.writer(f).writerows(rows)

with open("grades.csv") as f:
    reader = csv.DictReader(f)
    for row in reader:
        avg = (int(row["Math"]) + int(row["Science"])) / 2
        print(f"{row['Name']}: {avg}")

Output

Ana: 89.5
Ben: 79.0
Carla: 94.0

Open grades.csv in Excel and you'll see a neat table. This is a very practical skill: Python can process a class record faster than doing it by hand.

Handling missing files

try:
    with open("highscore.txt") as f:
        high = int(f.read())
except FileNotFoundError:
    high = 0
print("High score:", high)

Output

High score: 0

The first time the program runs, the file doesn't exist yet, so we start at 0 instead of crashing. More about try in the next lesson.

Text encoding

If your file contains ñ, emojis or other special characters, open it with encoding="utf-8" to avoid strange characters, especially on Windows:

with open("mga-pangalan.txt", "w", encoding="utf-8") as f:
    f.write("Niño, Peña, Señora 😊\n")

Quick Quiz

Check what you learned. Walang grade ito, practice lang. 🙂

1. Which mode adds to the end of a file without erasing it?
2. What does with open(...) as f: do automatically?
3. What does opening an existing file with "w" do?
4. Which error happens when reading a file that doesn't exist?

By Sir Reyel · Last updated 2026-12-04