Unays Learn · Python

Reading and writing files in Python, including CSV

Programs forget everything when they stop, unless they save data to a file. This tutorial shows how to write and read text files and CSV spreadsheets safely.

Writing a text file

with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("First line\n")
    f.write("Second line\n")

"w" means write, which replaces the file if it exists. Use "a" to add to the end instead. The with block closes the file automatically, even if an error happens. Always set encoding="utf-8" so letters such as ë and ç are saved correctly.

Reading a text file

with open("notes.txt", encoding="utf-8") as f:
    for number, line in enumerate(f, start=1):
        print(number, line.rstrip("\n"))

Looping over the file reads one line at a time, which works even for very large files. Each line ends with a newline character, so rstrip("\n") removes it. To read everything at once, use f.read().

When the file does not exist

try:
    with open("settings.txt", encoding="utf-8") as f:
        settings = f.read()
except FileNotFoundError:
    settings = ""
    print("No settings yet, using defaults.")

CSV spreadsheets

CSV (comma-separated values) files open in any spreadsheet app. Python's csv module handles commas inside values and quoting for you:

import csv

rows = [
    {"name": "Arta", "subject": "Math", "score": 92},
    {"name": "Besa", "subject": "Math", "score": 67},
    {"name": "Dren", "subject": "Science", "score": 88},
]

with open("scores.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "subject", "score"])
    writer.writeheader()
    writer.writerows(rows)

with open("scores.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        print(row["name"], int(row["score"]))

Everything read from a CSV is text, so convert numbers with int() or float(). The newline="" argument prevents blank lines between rows on Windows.

Project: class averages

import csv
from collections import defaultdict

totals = defaultdict(list)
with open("scores.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        totals[row["subject"]].append(int(row["score"]))

for subject, scores in sorted(totals.items()):
    print(f"{subject}: average {sum(scores) / len(scores):.1f} (scores counted: {len(scores)})")

defaultdict(list) creates an empty list the first time a new subject appears, so you do not need to check whether the key exists.

Try it yourself

In Unays Code, write a small diary program that adds a dated line to diary.txt each time it runs and then prints the last three entries.

This tutorial was written with AI assistance and reviewed by Unays. The runnable code examples were tested before publishing. Spotted a mistake? Tell us at [email protected].