Python Tutorial · Working with Data · Lesson 37 of 42
Python File Handling
Read and write text files, CSV and paths safely with with-statements and pathlib.
Open, read and write
Use with open(...) — it closes the file automatically, even if an error occurs.
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("first line\n")
f.write("second line\n")
with open("notes.txt", "a", encoding="utf-8") as f:
f.write("appended line\n")
with open("notes.txt", encoding="utf-8") as f:
print(f.read())
Output
first line second line appended line
| Mode | Meaning |
|---|---|
"r" |
read (default) |
"w" |
write (overwrites) |
"a" |
append |
"x" |
create, fail if it exists |
"b" |
binary, e.g. "rb" |
Always pass encoding="utf-8" for text files.
Reading line by line
Iterating over a file reads one line at a time — memory-friendly for large files.
with open("log.txt", "w", encoding="utf-8") as f:
f.write("INFO start\nERROR disk full\nINFO retry\nERROR timeout\n")
with open("log.txt", encoding="utf-8") as f:
errors = [line.strip() for line in f if line.startswith("ERROR")]
print(errors)
Output
['ERROR disk full', 'ERROR timeout']
CSV and pathlib
import csv
from pathlib import Path
path = Path("people.csv")
with path.open("w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["name", "city"])
writer.writerows([["Ada", "London"], ["Linus", "Helsinki"]])
with path.open(encoding="utf-8") as f:
for row in csv.DictReader(f):
print(row["name"], "lives in", row["city"])
print(path.exists(), path.stat().st_size, "bytes")
Output
Ada lives in London Linus lives in Helsinki True 39 bytes
Test yourself
Which mode opens a file for appending?
"r""w""a""x"
Show answer
Answer: "a"