Reading and writing files
Read text and CSV files line by line in Python, write and append to files with open() and with, and use the csv module to load and save spreadsheet data.
🎯 By the end of this lesson you will be able to:
- Open, read and write text files safely with `with open(...)`
- Choose the right mode: read, write or append
- Read and write CSV files with the csv module
Outline
What you'll learn and why it matters
When a program ends, its variables disappear. To keep data between runs (an expense list, a high score, a report), programs save it in files. Reading files also lets your programs work on data from other places, such as a spreadsheet exported as CSV. This is one of the most practical skills in the course.
Get the sample files
Download these two small files and save them in the same folder as your Python programs (your python-course folder). When you run a program from IDLE, Python looks for files in the program's own folder.
⬇ Download marks.txtFive students and their marks, one per line.
⬇ Download expenses.csvA week of made-up expenses in CSV format.
Open marks.txt in a text editor such as Notepad to see what is inside:
Asha,78
Ravi,91
Meera,66
John,84
Fatima,72Reading a file line by line
with open("marks.txt") as file:
for line in file:
print(line.strip())Output
Asha,78 Ravi,91 Meera,66 John,84 Fatima,72
| Part | Meaning |
|---|---|
open("marks.txt") | Opens the file for reading and gives you a file object. |
with ... as file: | Uses the file inside the indented block and closes it automatically afterwards, even if something goes wrong. |
for line in file: | A file can be looped over, one line at a time. |
line.strip() | Each line ends with an invisible newline character (\n). strip() removes it, so print does not add blank lines. |
Worked example: average marks from a file
Each line is a string like "Asha,78". split(",") breaks it at the comma into a list ["Asha", "78"], and int() turns the mark into a number:
total = 0
count = 0
best_name = ""
best_mark = 0
with open("marks.txt") as file:
for line in file:
name, mark = line.strip().split(",")
mark = int(mark)
total += mark
count += 1
if mark > best_mark:
best_name = name
best_mark = mark
print(f"Students: {count}")
print(f"Average: {total / count:.1f}")
print(f"Top: {best_name} with {best_mark}")Output
Students: 5 Average: 78.2 Top: Ravi with 91
name, mark = ["Asha", "78"] unpacks the two-item list into two variables, just like unpacking pairs in the last lesson.
Writing and appending
Pass a second argument, the mode, to choose what open does:
| Mode | Meaning | If the file exists | If it does not |
|---|---|---|---|
"r" (default) | read | reads it | error |
"w" | write | empties it first, then writes | creates it |
"a" | append | adds to the end | creates it |
with open("report.txt", "w") as file:
file.write("Class report\n")
file.write("Average: 78.2\n")
with open("report.txt", "a") as file:
file.write("Checked by: Ms Rao\n")
with open("report.txt") as file:
print(file.read())Output
Class report Average: 78.2 Checked by: Ms Rao
write() does not add a new line for you, so end each line with \n. file.read() reads the whole file into one string.
CSV files and the csv module
CSV (comma-separated values) is a plain-text table: the first line holds the column names and each following line is a row. Excel and Google Sheets can open and save CSV. Here is the start of expenses.csv:
date,category,description,amount
2026-11-01,Food,Groceries,850.50
2026-11-02,Transport,Metro card top-up,500You could split each line on commas yourself, but a description might contain a comma. Python's built-in csv module handles all of that. csv.DictReader turns every row into a dictionary using the header names as keys:
import csv
total = 0
with open("expenses.csv", newline="") as file:
for row in csv.DictReader(file):
amount = float(row["amount"])
total += amount
print(f"{row['date']} {row['category']:<10} {amount:>8.2f}")
print(f"Total spent: {total:.2f}")Output
2026-11-01 Food 850.50 2026-11-02 Transport 500.00 2026-11-03 Food 420.00 2026-11-05 Bills 299.00 2026-11-07 Study 210.00 2026-11-08 Transport 150.00 2026-11-10 Food 365.75 Total spent: 2795.25
import csv loads the module (more on this in lesson 14). In the f-string, :<10 pads text to 10 characters wide and :>8.2f right-aligns a number in 8 characters with 2 decimals, which lines the columns up neatly.
To add a row, open the file in append mode and use csv.writer:
import csv
with open("expenses.csv", "a", newline="") as file:
writer = csv.writer(file)
writer.writerow(["2026-11-11", "Food", "Tea and snacks", 60])
with open("expenses.csv") as file:
lines = file.readlines()
print(f"The file now has {len(lines)} lines.")
print(lines[-1].strip())Output
The file now has 9 lines. 2026-11-11,Food,Tea and snacks,60
Practice
Guided exercise
Students above average
Read marks.txt into a dictionary of name → mark. Then print the names of students who scored above the class average.
- Create an empty dictionary
marks = {}. - Loop over the file lines, split each one and store
marks[name] = int(mark). - Work out the average with
sum(marks.values()) / len(marks). - Loop over
marks.items()and print names above the average.
Show the solution
marks = {}
with open("marks.txt") as file:
for line in file:
name, mark = line.strip().split(",")
marks[name] = int(mark)
average = sum(marks.values()) / len(marks)
print(f"Average: {average:.1f}")
for name, mark in marks.items():
if mark > average:
print(name)Output
Average: 78.2 Ravi John
How to get there: Reading the whole file into a dictionary first means you can work out the average before deciding who is above it. Asha's 78 is just below 78.2.
Your turn
Spending per category
Use csv.DictReader on expenses.csv and the dictionary-totals pattern from lesson 11 to print how much was spent in each category.
Show the solution
import csv
totals = {}
with open("expenses.csv", newline="") as file:
for row in csv.DictReader(file):
category = row["category"]
totals[category] = totals.get(category, 0) + float(row["amount"])
for category, total in totals.items():
print(f"{category}: {total:.2f}")Output
Food: 1636.25 Transport: 650.00 Bills: 299.00 Study: 210.00
How to get there: Every value read from a CSV is a string, so convert amount with float() before adding. This is almost exactly the summary feature of your final project.
Common mistakes
The file is in a different folder
You see: FileNotFoundError: [Errno 2] No such file or directory: 'marks.txt'
Fix: Save the data file in the same folder as your program and run it from there, or give the full path.
Using "w" when you meant "a"
You see: Old data disappears
Fix: Use "a" to add. Keep a backup copy of important files while learning.
Doing maths on values read from a file
You see: TypeError: can only concatenate str (not "int") to str
Fix: Everything read from a text or CSV file is a string; convert with int() or float().
Forgetting \n when writing
You see: All your lines end up joined on one line
Fix: End every write() with \n, or use csv.writer.
Recap
with open(name) as file:opens a file and closes it automatically.- Loop over a file to read it line by line;
strip()removes the newline at the end. - Mode
"w"replaces a file's contents,"a"adds to the end,"r"(default) reads. - Use
csv.DictReaderandcsv.writer(withnewline="") for CSV files, and convert numbers yourself.
Key terms
- CSV
- Comma-separated values: a plain-text table that spreadsheets can open.
- Mode
- How a file is opened: "r" read, "w" write (replace), "a" append.
- Working directory
- The folder Python looks in for files given without a full path.
Check your understanding
Answer all 4 questions, then check your answers to see an explanation for each one.
1. Which mode adds new lines to the end of an existing file without deleting what is there?
2. Why is `with open(...) as file:` recommended?
3. You read the line `"Ravi,91\n"`. What does `line.strip().split(",")` give?
4. You see `FileNotFoundError` for expenses.csv. What is the most likely cause?
Read more
Mark this lesson complete
Finished this lesson?
When you have worked through the examples and exercises, mark it complete to save your progress.