Topic 10 / 15
Files, Paths & JSON
Always Use with
The with statement guarantees the file closes, even if an exception is thrown halfway through:
# read an entire file
with open("notes.txt", encoding="utf-8") as f:
content = f.read()
# read line by line (memory-friendly for big files)
with open("notes.txt", encoding="utf-8") as f:
for line in f:
print(line.rstrip())Writing
with open("log.txt", "w", encoding="utf-8") as f: # w = overwrite
f.write("first line\n")
with open("log.txt", "a", encoding="utf-8") as f: # a = append
f.write("another line\n")Modes: "r" read (default), "w" write/truncate, "a" append, "rb"/"wb" binary. Always pass encoding="utf-8" — don’t depend on the OS default.
pathlib — Modern Path Handling
Stop concatenating path strings. Path objects handle separators, names, and globbing across operating systems:
from pathlib import Path
base = Path("projects") / "coding-india" # joins with the right separator
base.mkdir(parents=True, exist_ok=True)
p = base / "data.json"
p.exists() # False
p.suffix # '.json'
p.stem # 'data'
# read/write tiny files in one call
p.write_text('{"ok": true}', encoding="utf-8")
print(p.read_text(encoding="utf-8"))
# find files
for f in base.glob("**/*.py"): # recursive glob
print(f)JSON — the Data Format of the Web
import json
user = {"name": "Ravi", "score": 82, "tags": ["python", "django"]}
# Python → JSON string
text = json.dumps(user, indent=2)
# JSON string → Python
data = json.loads(text)
data["score"] # 82
# straight to/from files
with open("user.json", "w", encoding="utf-8") as f:
json.dump(user, f, indent=2)
with open("user.json", encoding="utf-8") as f:
user = json.load(f)Mapping: JSON object ⇄ dict, array ⇄ list, null ⇄ None, true/false ⇄ True/False. Remember: dumps/loads work with strings, dump/load with files.
CSV
import csv
with open("scores.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
print(row["name"], row["score"]) # each row is a dictFor serious tabular work, this is where pandas takes over — covered in the Data Science series.