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
| Mode | Meaning |
|---|---|
| "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.
# ✅ Correct — auto-closeswith open("notes.txt") as f:text = f.read()# ❌ Risky — no auto-close, leaks the handle on exceptionf = open("notes.txt")text = f.read()f.close()
Reading text
# Whole file at once — careful with huge fileswith open("notes.txt") as f:text = f.read()# Line by line — efficient even for 10GB fileswith open("logs.txt") as f:for line in f:print(line.rstrip()) # rstrip removes the trailing newline# All lines at once into a listwith open("config.txt") as f:lines = f.readlines()# Specify encoding when in doubt — utf-8 is the right defaultwith open("emoji.txt", encoding="utf-8") as f:print(f.read())
Writing text
# Overwrite (or create)with open("output.txt", "w", encoding="utf-8") as f:f.write("Hello, Albero!\n")f.write("Line 2\n")# Appendwith open("log.txt", "a") as f:f.write(f"{user_id} logged in\n")# Write many lines at oncelines = ["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(",").
import csv# Readwith open("orders.csv", encoding="utf-8") as f:reader = csv.DictReader(f)for row in reader:print(row["customer"], "→", row["amount"])# Writerows = [{"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
import json# Readwith open("config.json") as f:config = json.load(f)print(config["api_url"])# Writedata = {"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 stringback = 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.
from pathlib import Path# Build a pathdata_dir = Path.home() / "Albero" / "data"notes = data_dir / "notes.txt"# Useful methodsprint(notes.exists()) # True / Falseprint(notes.is_file()) # Trueprint(notes.suffix) # '.txt'print(notes.stem) # 'notes'print(notes.parent) # /Users/aanya/Albero/data# Read/write directly — no open() needed for simple casesnotes.write_text("Hello!\n", encoding="utf-8")print(notes.read_text(encoding="utf-8"))# Iterate over files in a folderfor csv_file in data_dir.glob("*.csv"):print(csv_file.name)
Key takeaways
- 01Always open files inside a with-statement — guarantees auto-close.
- 02Pass encoding="utf-8" explicitly; never trust the system default.
- 03For huge files, iterate line-by-line — never .read() the whole thing.
- 04Use the csv module for simple work; pandas.read_csv for analytics.
- 05json.load / json.dump handle files; json.loads / json.dumps handle strings.
- 06Reach for pathlib over os.path — cleaner API, cross-platform out of the box.
