JSON, CSV & pathlib
Beginnerjson.load/dump round-trip Python dicts to the web's data format, csv handles tabular files safely, and pathlib replaces string paths with a clean object API.
Overview
Three standard-library modules cover 90% of data plumbing. json maps Python dict/list/str/int/bool/None to the format every API speaks — with loads/dumps for strings and load/dump for files. csv reads and writes tabular data (never split(",") yourself — quoted fields will break you). pathlib.Path makes paths objects: joining with /, globbing, reading with one method — and it works identically on Windows and Linux.
JSON in Four Functions
loads/dumps = string ↔ object; load/dump = file ↔ object. indent pretty-prints; JSON keys are always strings; tuples become lists; datetime needs manual conversion.
import json
profile = {"name": "Asha", "skills": ["python", "sql"], "cgpa": 8.7}
s = json.dumps(profile, indent=2) # dict -> pretty string
print(s)
back = json.loads(s) # string -> dict
print(back["skills"][0]) # python
with open("profile.json", "w") as f: # dict -> file
json.dump(profile, f, indent=2)
with open("profile.json") as f: # file -> dict
data = json.load(f)
# Gotchas
json.dumps({1: "a"}) # keys stringified: '{"1": "a"}'
json.dumps((1, 2)) # tuples become lists: '[1, 2]'
# json.dumps(datetime.now()) -> TypeError: use .isoformat() firstCSV + pathlib
csv.DictReader gives each row as a dict keyed by the header. Path objects join with /, glob patterns, and read/write in one call.
import csv
from pathlib import Path
# students.csv: name,branch,cgpa
with open("students.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
print(row["name"], float(row["cgpa"]))
with open("toppers.csv", "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=["name", "cgpa"])
w.writeheader()
w.writerow({"name": "Neha", "cgpa": 9.4})
# pathlib — paths as objects
base = Path("data")
report = base / "2026" / "report.txt" # joining with /
report.parent.mkdir(parents=True, exist_ok=True)
report.write_text("hello", encoding="utf-8")
print(report.read_text(encoding="utf-8")) # hello
print(report.suffix, report.stem) # .txt report
for py in Path(".").glob("**/*.py"): # recursive find
passKey Points to Remember
- 1json: loads/dumps for strings, load/dump for files; keys become strings, tuples become lists
- 2Use csv module (DictReader/DictWriter) — never split(",") manually
- 3pathlib.Path joins with /, globs, mkdirs, and read_text/write_text in one call
- 4Always newline="" when opening CSV files (per the csv docs) and encoding="utf-8"
Interview Questions
Sign in to ask AriaDifference between json.load and json.loads?
Why should you use the csv module instead of line.split(",")?
Ask Aria about JSON, CSV & pathlib
Your personal AI tutor — ask anything about this concept
Revision Status
Personal Notes
Sign in to save personal notes for this topic.
Discussion
Sign in to join the discussion.