Python File Handling: Read, Write, JSON and CSV
Part 10 of the Python for Everyone track. Last updated: September 2026.
File I/O in Python boils down to one rule: always use with open(...). Everything else — text vs binary, JSON, CSV, paths — builds on that.
Reading and writing text files
# Writing (overwrites existing content)
with open("notes.txt", "w") as f:
f.write("Line one\n")
f.write("Line two\n")
# Appending
with open("notes.txt", "a") as f:
f.write("Line three\n")
# Reading — three flavors
with open("notes.txt") as f:
whole = f.read() # one big string
with open("notes.txt") as f:
lines = f.readlines() # list of lines
with open("notes.txt") as f:
for line in f: # iterate directly — memory-friendly for big files
print(line.strip())
The with block closes the file automatically, even if an error occurs. Manual f.close() is legacy style.
Modes cheat sheet
- "r" — read (default; errors if file missing)
- "w" — write (creates or overwrites)
- "a" — append (creates if missing)
- "rb" / "wb" — binary mode for images, PDFs, etc.
- Add encoding="utf-8" when working with non-ASCII text
Paths the modern way: pathlib
from pathlib import Path
p = Path("data") / "notes.txt" # / joins paths — works on every OS
print(p.exists()) # True/False
print(p.name, p.suffix, p.parent) # notes.txt .txt data
text = p.read_text() # read whole file in one call
p.write_text("hello") # write whole file in one call
for f in Path(".").glob("*.py"): # find files by pattern
print(f)
Prefer pathlib over string-concatenated paths and os.path — it's cleaner and cross-platform.
JSON: Python's native data format
import json
user = {"name": "Ada", "scores": [95, 88]}
# Write
with open("user.json", "w") as f:
json.dump(user, f, indent=2)
# Read
with open("user.json") as f:
loaded = json.load(f) # back to a dict
# Strings instead of files
s = json.dumps(user) # dict → string
d = json.loads(s) # string → dict
Mnemonic: dump/load = files, dumps/loads = strings (the "s" is for string).
CSV files
import csv
# Writing
with open("users.csv", "w", newline="") as f:
w = csv.DictWriter(f, fieldnames=["name", "age"])
w.writeheader()
w.writerow({"name": "Ada", "age": 36})
# Reading
with open("users.csv") as f:
for row in csv.DictReader(f): # each row is a dict
print(row["name"], row["age"])
Always pass newline="" when opening CSV files for writing — otherwise you get blank rows on Windows.
Key takeaways
- Always with open(...) — never manage close() manually.
- pathlib for paths; json.dump/load for JSON; csv module with newline="".
- Iterate large files line-by-line instead of read().
Next in this series: Python Exception Handling: try/except/else/finally and raise.
Comments
Post a Comment