Skip to main content
Albero Academy

Python File Handling

Read and write text files, CSVs, and JSON in Python — with safe context managers, common modes, and Pathlib best practices.

Chapter 11Python16 min readBeginner friendly
  • #Python
  • #File I/O
  • #CSV
  • #JSON

Reading from disk is one of the first things any program needs to do — log files, data dumps, config, CSVs from analysts. Python makes it short and safe. The golden rule: always use a with block.

open() and modes

ModeMeaning
"r"read text (default)
"w"write text — overwrites existing file
"a"append text
"x"create new file — fails if it exists
"rb" / "wb"binary read / write
"r+"read AND write

The with-statement

Always open files inside a with block. The file is automatically closed when the block exits — even if an exception is raised inside.

Python
# ✅ Correct — auto-closes
with open("notes.txt") as f:
text = f.read()
# ❌ Risky — no auto-close, leaks the handle on exception
f = open("notes.txt")
text = f.read()
f.close()

Reading text

Python
# Whole file at once — careful with huge files
with open("notes.txt") as f:
text = f.read()
# Line by line — efficient even for 10GB files
with open("logs.txt") as f:
for line in f:
print(line.rstrip()) # rstrip removes the trailing newline
# All lines at once into a list
with open("config.txt") as f:
lines = f.readlines()
# Specify encoding when in doubt — utf-8 is the right default
with open("emoji.txt", encoding="utf-8") as f:
print(f.read())

Writing text

Python
# Overwrite (or create)
with open("output.txt", "w", encoding="utf-8") as f:
f.write("Hello, Albero!\n")
f.write("Line 2\n")
# Append
with open("log.txt", "a") as f:
f.write(f"{user_id} logged in\n")
# Write many lines at once
lines = ["one\n", "two\n", "three\n"]
with open("nums.txt", "w") as f:
f.writelines(lines)

CSV files

The standard library's csv module handles quoting and escaping correctly. Don't roll your own with split(",").

Python
import csv
# Read
with open("orders.csv", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["customer"], "→", row["amount"])
# Write
rows = [
{"name": "Aanya", "score": 92},
{"name": "Karan", "score": 87}
]
with open("scores.csv", "w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["name", "score"])
writer.writeheader()
writer.writerows(rows)

JSON files

Python
import json
# Read
with open("config.json") as f:
config = json.load(f)
print(config["api_url"])
# Write
data = {"name": "Aanya", "scores": [92, 87, 95]}
with open("out.json", "w") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
# Strings (not files)
text = json.dumps(data) # dict -> JSON string
back = json.loads('{"x": 1, "y": 2}') # JSON string -> dict

Pathlib — modern paths

Forget os.path.join — pathlib is cleaner, type-safe, and works the same on Windows / macOS / Linux.

Python
from pathlib import Path
# Build a path
data_dir = Path.home() / "Albero" / "data"
notes = data_dir / "notes.txt"
# Useful methods
print(notes.exists()) # True / False
print(notes.is_file()) # True
print(notes.suffix) # '.txt'
print(notes.stem) # 'notes'
print(notes.parent) # /Users/aanya/Albero/data
# Read/write directly — no open() needed for simple cases
notes.write_text("Hello!\n", encoding="utf-8")
print(notes.read_text(encoding="utf-8"))
# Iterate over files in a folder
for csv_file in data_dir.glob("*.csv"):
print(csv_file.name)

Key takeaways

  1. 01Always open files inside a with-statement — guarantees auto-close.
  2. 02Pass encoding="utf-8" explicitly; never trust the system default.
  3. 03For huge files, iterate line-by-line — never .read() the whole thing.
  4. 04Use the csv module for simple work; pandas.read_csv for analytics.
  5. 05json.load / json.dump handle files; json.loads / json.dumps handle strings.
  6. 06Reach for pathlib over os.path — cleaner API, cross-platform out of the box.