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 file is just data living outside your program, on disk, that survives after the program ends —
open()is how Python connects to it. - Sub-topics build on each other — reading first, then writing, then the full picture of modes and paths, then the
csvmodule for structured data, then handling the exceptions files can raise, then combining all of it into one real workflow. - This is where Chapter 12's
try/exceptbecomes essential again — files fail to open far more often than numbers fail to divide, and production code has to expect that.
1. Opening & reading files
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
withstatement is the standard way to open a file — it closes the file automatically, even if something goes wrong.
Picture a plain text file called notes.txt, sitting in
the same folder as a script, with three lines in it:
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:
with open("notes.txt") as file:
contents = file.read()
print(contents)
Buy milk
Call the bank
Finish the report
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.
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:
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:
with open("notes.txt") as file:
for line in file:
print("Task:", line.strip())
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:
with open("notes.txt") as file:
lines = file.readlines()
print(lines)
print("Number of tasks:", len(lines))
['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.
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.withis the standard way to open a file — it closes automatically, even if an error happens inside the block.
2. Writing to files
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.
By default, open() only allows reading. Writing needs
a second argument telling Python what to do with the file:
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())
Eggs
Bread
Coffee
"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.
with open("shopping_list.txt", "a") as file:
file.write("Butter\n")
with open("shopping_list.txt") as file:
print(file.read())
Eggs
Bread
Coffee
Butter
"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:
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())
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.
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.
3. File modes & paths
- 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.
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:
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())
Counter is now: 1
"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.
"r"— read only; the default if no mode is given at all."w"— write only; erases existing content immediately."a"— append only; adds after existing content."r+"— read and write, without erasing first.
Every example so far has also been in text mode, which is the default and treats a file's contents as ordinary strings.
.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.
"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.
- 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.
4. The csv module
- 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.writerandcsv.DictReader/csv.DictWriterhandle this correctly, every time.
.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:
line = 'Widget,"Acme, Inc.",19.99'
fields = line.split(",")
print(fields)
print("Number of fields:", len(fields))
['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.
Given a small CSV file of sales data, csv.reader
parses each row correctly, quotes and all:
product,supplier,price
Widget,"Acme, Inc.",19.99
Gadget,BetaCorp,34.50
Gizmo,"Global Parts, Ltd.",12.00
import csv
with open("sales.csv") as file:
reader = csv.reader(file)
for row in reader:
print(row)
['product', 'supplier', 'price']
['Widget', 'Acme, Inc.', '19.99']
['Gadget', 'BetaCorp', '34.50']
['Gizmo', 'Global Parts, Ltd.', '12.00']
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:
import csv
with open("sales.csv") as file:
reader = csv.DictReader(file)
for row in reader:
print(row["product"], "-", row["price"])
Widget - 19.99
Gadget - 34.50
Gizmo - 12.00
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:
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())
product,quantity
Widget,4
Gadget,2
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:
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())
product,quantity
Widget,4
Gadget,2
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.
- Hand-splitting on commas breaks when a field itself contains a comma; the
csvmodule doesn't. csv.reader/csv.writerwork with lists per row;csv.DictReader/csv.DictWriterwork with dictionaries, using the header row as keys.- Always pass
newline=""when opening a file forcsv.writerorcsv.DictWriter.
5. Handling file-related exceptions
FileNotFoundErroris raised whenopen()is asked for a file that doesn't exist.PermissionErroris raised when the program isn't allowed to read or write a file it otherwise found fine.- This is Chapter 12's
try/exceptpattern again —open()is simply one more risky operation to wrap.
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:
with open("missing_file.txt") as file:
print(file.read())
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:
try:
with open("missing_file.txt") as file:
print(file.read())
except FileNotFoundError:
print("That file doesn't exist yet.")
That file doesn't exist yet.
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:
try:
with open("missing_file.txt") as file:
print(file.read())
except FileNotFoundError as e:
print("Could not open file:", e)
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.
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:
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"))
'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."
FileNotFoundErrorfires whenopen()is given a path that doesn't exist.PermissionErrorfires when the file exists but access is denied.- Both follow Chapter 12's exact
try/exceptpattern —open()is just one more operation that can fail.
6. Real-world file & CSV processing in production
- 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.
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:
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:
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())
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.
- A missing or unreadable log file is caught and reported, instead of crashing the entire report job.
withguarantees every file — the log being read and the report being written — gets closed properly, even if something above it fails.- The output is a real CSV file, ready to open in a spreadsheet or feed into another program — the same shape data takes throughout real software systems.
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.
- Real file processing combines defensive
try/except, plain Python logic, and thecsvmodule for output. withprevents 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.
- Nearly every business tool exports and imports CSV at some point — sales reports, customer lists, financial data — because it's a plain-text format every spreadsheet and database already understands.
- Server and application logs, exactly like Sub-topic 6's
app.log, are how real engineering teams diagnose problems after the fact — turning raw log lines into a summarized report is one of the most common real scripting tasks there is. - Long-running production programs — web servers, scheduled batch jobs, data pipelines — depend on
with's automatic cleanup specifically because they can't afford a slow file-handle leak building up over days or weeks of continuous operation.
Points to Remember
open("filename")returns a file object;.read(), looping over the file, and.readlines()all read its contents, andwithis the standard way to open any file — it closes automatically, even on error."w"mode erases a file's existing content immediately;"a"mode appends after it instead..write()never adds a newline on its own.- The core modes are
"r","w","a", and"r+"; text mode handles strings and is the default, binary mode handles raw bytes; a relative path is resolved from the current working directory, not necessarily the script's own folder. - The
csvmodule reads and writes tabular data correctly, even when fields contain commas —csv.reader/csv.writeruse lists per row,csv.DictReader/csv.DictWriteruse dictionaries keyed by column name. FileNotFoundErrorandPermissionErrorare caught with the sametry/exceptpattern from Chapter 12 —open()is simply one more operation that can fail.- Real file and CSV processing combines all of this: defensive exception handling around reading, plain Python for processing, and the
csvmodule for output — always insidewithto prevent file-handle leaks.