🐍 Python for Everyone

← Back to all chapters

Chapter 13 of 27 Intermediate 50 min read

File Handling & CSV

Every program you've written so far forgets everything the moment it stops running. Variables, lists, results — all of it disappears the instant the script ends. Real programs need to remember things between runs: a saved high score, a list of customers, a log of what happened last night. This chapter is about reading and writing actual files on disk — plain text files and the csv format that spreadsheets and databases use everywhere — so your programs can finally hold onto data.

How to read this chapter

A to-do list app that forgets your tasks the moment you close it isn't very useful. Neither is a game that forgets your high score, or a business tool that forgets every customer it's ever seen. The only difference between a program that remembers and one that doesn't is whether it saves its data to a file — and that's exactly what this chapter teaches.
Sub-topic 1 of 6

1. Opening & reading files

At a glance
  • open("filename") gives your program a connection to a file on disk, called a file object.
  • .read(), .readline(), and .readlines() pull text out of that file in different shapes.
  • The with statement is the standard way to open a file — it closes the file automatically, even if something goes wrong.
Why this matters: every example before this chapter has lived entirely in memory. The moment a script ends, that data is gone. Files are how a program's data outlives the program itself.

Picture a plain text file called notes.txt, sitting in the same folder as a script, with three lines in it:

notes.txt — a plain text file, one task per line
Buy milk
Call the bank
Finish the report

open() connects a Python program to that file so its contents can be read into a string:

read_whole_file.py
with open("notes.txt") as file:
    contents = file.read()

print(contents)
actual output of read_whole_file.py
Buy milk
Call the bank
Finish the report
What is... a file object? A file object is what open() returns — a live connection to a file on disk. It's not the file's text itself; it's the thing your program reads from (or writes to) using methods like .read().

Notice the with keyword wrapping the whole thing. That part isn't optional style — it's the standard, expected way to open any file in Python, and the next few paragraphs explain exactly why.

What is... the with statement? with open("notes.txt") as file: opens the file, runs the indented block below it, and then automatically closes the file when that block ends — even if an error happens partway through. file is just a variable name holding the file object, same as any other variable.

"Automatic cleanup" means the file gets closed the instant the with block finishes, with no extra line of code needed. Compare that to opening a file the manual way:

no_with_demo.py
file = open("notes.txt")
contents = file.read()
file.close()

print(contents)

This works, but it has a real risk: if anything raises an exception between open() and file.close(), that close() line never runs, and the file stays open longer than it should. An open file that never gets closed is called a file handle leak — a real problem in programs that open many files over a long run, since operating systems only allow so many open files at once. with closes the file no matter what happens inside the block, so this failure mode simply can't occur.

Reading a whole file into one string works for small files, but a to-do list is really a list of separate lines. Looping over a file object directly gives one line at a time:

read_lines_loop.py
with open("notes.txt") as file:
    for line in file:
        print("Task:", line.strip())
actual output of read_lines_loop.py
Task: Buy milk
Task: Call the bank
Task: Finish the report

.strip() removes the invisible newline character (\n) that ends every line in the file — without it, each printed task would have a stray blank line after it.

.readlines() is another option — it reads the whole file at once, but returns a list of lines instead of one big string:

readlines_demo.py
with open("notes.txt") as file:
    lines = file.readlines()

print(lines)
print("Number of tasks:", len(lines))
actual output of readlines_demo.py — note the \n still attached to each line
['Buy milk\n', 'Call the bank\n', 'Finish the report\n']
Number of tasks: 3
Go Deeper: .readline() reads just one line at a time

file.readline() (singular) reads only the next single line each time it's called, and returns an empty string once the file runs out of lines. It's rarely needed once you know the for-loop pattern above, but it exists for cases where a program needs to read a file's lines one at a time, on demand, rather than all at once.

Quick recap
  • open("filename") returns a file object connected to a file on disk.
  • .read() gets everything as one string; looping over the file, or .readlines(), gets it line by line.
  • with is the standard way to open a file — it closes automatically, even if an error happens inside the block.
Sub-topic 2 of 6

2. Writing to files

At a glance
  • open("filename", "w") opens a file for writing — and erases whatever was already in it.
  • open("filename", "a") opens a file for appending — new text is added after whatever's already there.
  • .write() puts text into the file; it doesn't add a newline automatically.
Use this when: a program needs to save data so it's still there the next time the program runs — a saved list, a log entry, a generated report.

By default, open() only allows reading. Writing needs a second argument telling Python what to do with the file:

write_mode_demo.py
with open("shopping_list.txt", "w") as file:
    file.write("Eggs\n")
    file.write("Bread\n")
    file.write("Coffee\n")

with open("shopping_list.txt") as file:
    print(file.read())
actual output of write_mode_demo.py
Eggs
Bread
Coffee
What is... write mode ("w")? "w" is the second argument to open() that means "I want to write to this file." If the file already has content, that content is erased the instant the file is opened — before a single new line is even written.

Notice each .write() call includes its own "\n" at the end. Unlike print(), .write() never adds a newline automatically — leaving it out means the next write lands on the same line.

Append mode solves a different problem: adding new data without losing what's already saved.

append_mode_demo.py
with open("shopping_list.txt", "a") as file:
    file.write("Butter\n")

with open("shopping_list.txt") as file:
    print(file.read())
actual output of append_mode_demo.py — Butter joins the existing list
Eggs
Bread
Coffee
Butter
What is... append mode ("a")? "a" opens a file so new writes are added after its existing content, instead of erasing it first. If the file doesn't exist yet, "a" creates it — the same as "w" would.

Mixing the two up is one of the most common real file-handling mistakes: opening a file in "w" mode when the goal was actually to add one more line wipes out everything that came before, permanently:

overwrite_warning_demo.py
with open("shopping_list.txt", "w") as file:
    file.write("Only this line survives now\n")

with open("shopping_list.txt") as file:
    print(file.read())
actual output of overwrite_warning_demo.py — Eggs, Bread, Coffee, and Butter are all gone
Only this line survives now

There's no undo for this — once "w" mode opens a file, the old content is unrecoverable. The rule to remember: "a" to add, "w" to replace everything.

Go Deeper: writing several lines at once with .writelines()

file.writelines(["Eggs\n", "Bread\n"]) writes a list of strings one after another, without adding newlines between them itself — each string still needs its own "\n" if a line break is wanted. It's a small convenience over calling .write() repeatedly, nothing more.

Quick recap
  • open("filename", "w") opens for writing and erases any existing content immediately.
  • open("filename", "a") opens for appending, adding new content after what's already there.
  • .write() never adds a newline on its own — include "\n" explicitly.
Sub-topic 3 of 6

3. File modes & paths

At a glance
  • The main modes are "r" (read, the default), "w" (write/overwrite), "a" (append), and "r+" (read and write, without erasing).
  • Text mode is the default and handles strings; binary mode ("rb"/"wb") handles raw bytes, for files that aren't plain text.
  • A relative path like "notes.txt" is resolved starting from wherever the script is actually run from — not necessarily the folder the script lives in.
Why this matters: "it works on my machine but not when someone else runs it" is very often a relative-path problem — understanding where Python looks for a file prevents that entire category of bug.

Sub-topics 1 and 2 already used three of the four common modes. "r+" is the one left — it opens a file for both reading and writing, without erasing it first, useful for a read-modify-write update to a small file:

rplus_demo.py
with open("counter.txt", "w") as file:
    file.write("0")

with open("counter.txt", "r+") as file:
    value = int(file.read())
    file.seek(0)
    file.write(str(value + 1))

with open("counter.txt") as file:
    print("Counter is now:", file.read())
actual output of rplus_demo.py
Counter is now: 1
What is... "r+" mode? "r+" opens a file for reading and writing at the same time, without erasing its existing content the way "w" does. file.seek(0) moves back to the start of the file before writing, since reading already moved the file's internal position to the end.

Every example so far has also been in text mode, which is the default and treats a file's contents as ordinary strings.

What is... text mode vs. binary mode? Text mode (the default) reads and writes ordinary strings, and is right for anything meant to be read as text — .txt, .csv, log files, and so on. Binary mode ("rb", "wb") reads and writes raw bytes instead, which is what's needed for files that aren't text at all — images, audio, PDFs. This chapter only works with text mode; binary mode is worth knowing exists, but isn't needed for anything here.

A relative path like "notes.txt", with no folder information at all, doesn't automatically mean "the same folder as my script." Python looks for it starting from the current working directory — wherever the python3 command was actually run from.

What is... a relative vs. absolute path? A relative path ("notes.txt") is resolved starting from the current working directory, and can point to a different file depending on where a program is run from. An absolute path ("/home/user/project/notes.txt") always points to the exact same file, no matter where the program was launched from.

This is exactly why this course's convention is to cd into an exercise's own folder before running it — every example and exercise in this chapter opens files using a plain relative filename, so it only finds them correctly when run from inside the same folder they live in.

Go Deeper: why absolute paths aren't just "the safer default"

Absolute paths avoid the working-directory problem entirely, but they hard-code one specific location on one specific computer — a path like /home/alice/project/notes.txt breaks the moment the project moves to a different folder or a different machine. Real projects usually solve this with relative paths run from a known, consistent working directory (exactly this chapter's convention), rather than hard-coded absolute ones.

Quick recap
  • The core modes: "r" read, "w" write/overwrite, "a" append, "r+" read-and-write.
  • Text mode (the default) handles strings; binary mode handles raw bytes for non-text files.
  • A relative path is resolved from the current working directory, which depends on where the script was run from — not where the script file lives.
Sub-topic 4 of 6

4. The csv module

At a glance
  • CSV (comma-separated values) is a plain-text format for tabular data — the format spreadsheets export to and databases import from constantly.
  • Hand-splitting a line on commas breaks the moment a field itself contains a comma.
  • csv.reader/csv.writer and csv.DictReader/csv.DictWriter handle this correctly, every time.
Why this matters: CSV is one of the most common data formats in real business software — exported spreadsheets, database dumps, and reports almost always land as a .csv file at some point.

A tempting shortcut is splitting each line on commas by hand, using .split(",") from earlier chapters. It looks fine until a field contains a comma of its own — like a company name:

naive_split_problem.py
line = 'Widget,"Acme, Inc.",19.99'
fields = line.split(",")

print(fields)
print("Number of fields:", len(fields))
actual output of naive_split_problem.py — one row became four fields instead of three
['Widget', '"Acme', ' Inc."', '19.99']
Number of fields: 4

The comma inside "Acme, Inc." was meant to be part of one field, quoted to protect it — but .split(",") has no idea quotes mean anything special. This is exactly the problem the csv module exists to solve.

What is... CSV? CSV stands for comma-separated values — a plain-text way to store tabular data, one row per line, fields separated by commas. A field that contains a comma is wrapped in quotes so it isn't mistaken for two separate fields. It's one of the most common formats for moving data between spreadsheets, databases, and programs.

Given a small CSV file of sales data, csv.reader parses each row correctly, quotes and all:

sales.csv — a small CSV file with a quoted field containing a comma
product,supplier,price
Widget,"Acme, Inc.",19.99
Gadget,BetaCorp,34.50
Gizmo,"Global Parts, Ltd.",12.00
csv_reader_demo.py
import csv

with open("sales.csv") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
actual output of csv_reader_demo.py — "Acme, Inc." stayed one field
['product', 'supplier', 'price']
['Widget', 'Acme, Inc.', '19.99']
['Gadget', 'BetaCorp', '34.50']
['Gizmo', 'Global Parts, Ltd.', '12.00']
What is... csv.reader? csv.reader(file) wraps an open file and yields one list of strings per row, correctly handling quoted fields — the exact thing .split(",") got wrong above. Each row is a plain list, so the header row ("product", "supplier", "price") is just the first list, not treated specially on its own.

Working with a list per row means remembering that row[0] is the product and row[2] is the price — easy to get wrong. csv.DictReader uses the header row to turn every row into a dictionary instead:

csv_dictreader_demo.py
import csv

with open("sales.csv") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row["product"], "-", row["price"])
actual output of csv_dictreader_demo.py
Widget - 19.99
Gadget - 34.50
Gizmo - 12.00
What is... csv.DictReader? csv.DictReader(file) reads the first row as column names automatically, then yields each following row as a dictionary — so row["product"] is far clearer than remembering that the product happens to be row[0].

Writing works the same way, in reverse. csv.writer takes rows as lists:

csv_writer_demo.py
import csv

rows = [
    ["product", "quantity"],
    ["Widget", 4],
    ["Gadget", 2],
]

with open("restock.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerows(rows)

with open("restock.csv") as file:
    print(file.read())
actual output of csv_writer_demo.py
product,quantity
Widget,4
Gadget,2
What is... the newline="" argument? newline="" tells Python not to add its own line endings when writing a CSV file, letting the csv module control line breaks itself. It's a small detail specific to writing CSV files — always include it whenever a file is opened for csv.writer or csv.DictWriter.

csv.DictWriter mirrors DictReader, writing a list of dictionaries instead of a list of lists:

csv_dictwriter_demo.py
import csv

records = [
    {"product": "Widget", "quantity": 4},
    {"product": "Gadget", "quantity": 2},
]

with open("restock_dict.csv", "w", newline="") as file:
    writer = csv.DictWriter(file, fieldnames=["product", "quantity"])
    writer.writeheader()
    writer.writerows(records)

with open("restock_dict.csv") as file:
    print(file.read())
actual output of csv_dictwriter_demo.py
product,quantity
Widget,4
Gadget,2
What is... fieldnames? fieldnames tells csv.DictWriter which dictionary keys to write, and in what column order. .writeheader() writes those names as the first row, matching what DictReader expects to find when reading the file back later.
Go Deeper: csv.reader and csv.writer aren't limited to commas

csv.reader(file, delimiter=";") reads a file that uses semicolons instead of commas to separate fields — some regions and tools export CSV-like files this way. The delimiter argument works for both reading and writing whenever a file doesn't use a plain comma.

Quick recap
  • Hand-splitting on commas breaks when a field itself contains a comma; the csv module doesn't.
  • csv.reader/csv.writer work with lists per row; csv.DictReader/csv.DictWriter work with dictionaries, using the header row as keys.
  • Always pass newline="" when opening a file for csv.writer or csv.DictWriter.
Sub-topic 5 of 6

5. Handling file-related exceptions

At a glance
  • FileNotFoundError is raised when open() is asked for a file that doesn't exist.
  • PermissionError is raised when the program isn't allowed to read or write a file it otherwise found fine.
  • This is Chapter 12's try/except pattern again — open() is simply one more risky operation to wrap.
Why this matters: unlike a typed-in number, a file's existence is completely outside a program's control — it can be deleted, renamed, or moved by someone else at any moment.

Every example so far has assumed the file being opened actually exists. Ask Python for a file that isn't there, and open() fails immediately:

filenotfound_crash.py
with open("missing_file.txt") as file:
    print(file.read())
actual output of filenotfound_crash.py — the program stops here
Traceback (most recent call last):
  File "filenotfound_crash.py", line 1, in <module>
    with open("missing_file.txt") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'missing_file.txt'

This is exactly Chapter 12's territory: an operation that can fail for reasons outside a program's control, wrapped in try/except so one missing file doesn't crash everything:

file_exception_demo.py
try:
    with open("missing_file.txt") as file:
        print(file.read())
except FileNotFoundError:
    print("That file doesn't exist yet.")
actual output of file_exception_demo.py — the program keeps running
That file doesn't exist yet.
What is... FileNotFoundError? FileNotFoundError is the exception Python raises when open() is asked for a file at a path that doesn't exist. It's caught exactly like ValueError was in Chapter 12 — try: open(...) except FileNotFoundError:.

Just like Chapter 12's as e, the exception object itself carries a useful message about exactly what went wrong:

file_exception_object_demo.py
try:
    with open("missing_file.txt") as file:
        print(file.read())
except FileNotFoundError as e:
    print("Could not open file:", e)
actual output of file_exception_object_demo.py
Could not open file: [Errno 2] No such file or directory: 'missing_file.txt'

A related exception, PermissionError, happens for a different reason — the file exists, but the operating system won't let the program open it. This shows up in real life more than it might seem: a file open in another program that's locked it, a folder a user account isn't allowed to write to, a system file that's read-only.

What is... PermissionError? PermissionError is raised when a file exists but the operating system denies the program access to it — for example, trying to write to a read-only file, or a folder the current user account doesn't have permission to modify.

Both exceptions can be caught together when a program's response to either one is the same:

multiple_file_exceptions.py
def load_config(filename):
    try:
        with open(filename) as file:
            return file.read()
    except FileNotFoundError:
        print(f"'{filename}' doesn't exist — using defaults.")
        return ""
    except PermissionError:
        print(f"Not allowed to read '{filename}' — using defaults.")
        return ""

print(load_config("missing_file.txt"))
actual output of multiple_file_exceptions.py
'missing_file.txt' doesn't exist — using defaults.
Go Deeper: why not just check if a file exists first?

It's tempting to check "does this file exist?" before opening it, but that check and the actual open() call happen at two different moments — the file could be deleted in between, however unlikely that sounds. Catching FileNotFoundError directly is both simpler and immune to that timing gap, which is why Python code almost always prefers "try it and catch the failure" over "check first."

Quick recap
  • FileNotFoundError fires when open() is given a path that doesn't exist.
  • PermissionError fires when the file exists but access is denied.
  • Both follow Chapter 12's exact try/except pattern — open() is just one more operation that can fail.
Sub-topic 6 of 6

6. Real-world file & CSV processing in production

At a glance
  • A realistic workflow reads a raw log file, counts what matters, and exports the result as a CSV report — combining every sub-topic in this chapter.
  • Context managers (with) matter even more in long-running programs, where a leaked file handle can pile up over hours or days.
  • File operations should always be wrapped defensively — a missing or unreadable file shouldn't be able to crash a whole batch job.
Pattern to remember: read defensively with try/except, process with plain Python, export with the csv module — always inside with.

Server logs are one of the most common real files a program processes — line after line of timestamped events, most routine, some worth flagging. A small slice of one might look like this:

app.log — a small slice of a server's log file
2026-07-01 10:02:15 INFO Server started
2026-07-01 10:03:41 ERROR Database connection timeout
2026-07-01 10:04:02 INFO User login: alice
2026-07-01 10:05:10 ERROR Database connection timeout
2026-07-01 10:06:33 WARNING Disk usage above 80%
2026-07-01 10:07:45 ERROR Invalid API key
2026-07-01 10:08:12 INFO User login: bob

A useful report counts how often each distinct error occurred, and saves that count as a CSV file another tool (or a spreadsheet) can open directly:

log_report.py
import csv

def count_error_types(log_filename):
    counts = {}
    try:
        with open(log_filename) as file:
            for line in file:
                if "ERROR" in line:
                    message = line.strip().split("ERROR", 1)[1].strip()
                    counts[message] = counts.get(message, 0) + 1
    except FileNotFoundError:
        print(f"Log file '{log_filename}' not found.")
        return {}
    return counts

def export_report(counts, report_filename):
    with open(report_filename, "w", newline="") as file:
        writer = csv.writer(file)
        writer.writerow(["error_message", "occurrences"])
        for message, occurrences in counts.items():
            writer.writerow([message, occurrences])

error_counts = count_error_types("app.log")
export_report(error_counts, "error_report.csv")

with open("error_report.csv") as file:
    print(file.read())
actual output of log_report.py
error_message,occurrences
Database connection timeout,2
Invalid API key,1

Notice how much of this chapter shows up in one small program: a with block reading the log line by line, a try/except guarding against a missing log file, plain-Python counting logic from earlier chapters, and csv.writer producing a clean report at the end.

The reason with matters even more here than in a short script: a batch job like this might run every night, for years, processing a new log file each time. If file handles ever leaked — left open because an exception skipped past a manual .close() — that leak would slowly accumulate every single run, eventually hitting the operating system's limit on open files and crashing the whole job. with makes that entire failure mode impossible, run after run, without anyone having to think about it again.

Go Deeper: this same pattern scales to much bigger jobs

Real production log processing works at a much larger scale — gigabytes of logs, dedicated logging services, databases instead of CSV files — but the core shape stays identical: read defensively, process the data, write the result somewhere durable. Everything in this chapter is the same pattern at a beginner's scale, using only files and the csv module.

Quick recap
  • Real file processing combines defensive try/except, plain Python logic, and the csv module for output.
  • with prevents file-handle leaks, which matter most in programs that run repeatedly over a long time.
  • A missing input file should be caught and reported, never allowed to crash an entire batch job.
In the Real World

Points to Remember

← All Chapters Take the Quiz →