Finding files with pathlib
from pathlib import Path
data = Path("data")
for f in sorted(data.iterdir()):
print(f"{f.name:<16} {f.stat().st_size:>5} bytes")
print((data / "orders.csv").exists(), (data / "orders.csv").suffix)customers.json 602 bytes events.jsonl 459 bytes orders.csv 505 bytes True .csv
Path("data") / "orders.csv" builds paths that work on Windows, macOS and Linux. Prefer pathlib over string paths.
Reading a file safely
with open("data/orders.csv", encoding="utf-8") as f: # "with" closes the file for you
header = f.readline().strip()
rows = [line.strip() for line in f]
print(header)
print(f"{len(rows)} data rows; first: {rows[0]}")order_id,customer_id,product,quantity,price,status,order_date 10 data rows; first: 101,1,Headphones,1,1999,DELIVERED,2026-04-01
CSV: read rows as dicts
import csv
with open("data/orders.csv", newline="", encoding="utf-8") as f:
reader = csv.DictReader(f) # each row becomes a dict keyed by the header
orders = list(reader)
print(orders[0])
print(type(orders[0]["quantity"])) # everything from CSV is text!{'order_id': '101', 'customer_id': '1', 'product': 'Headphones', 'quantity': '1', 'price': '1999', 'status': 'DELIVERED', 'order_date': '2026-04-01'}
<class 'str'>Notice 'quantity': '1' is a string. CSV has no types; you convert while cleaning.
CSV: clean and write
clean = []
for row in orders:
if not row["customer_id"] or not row["quantity"].isdigit():
continue # skip bad rows (lesson 6 keeps them)
clean.append({
"order_id": int(row["order_id"]),
"product": row["product"].strip(),
"status": row["status"].strip().upper(),
"amount": int(row["quantity"]) * int(row["price"]),
})
with open("orders_clean.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["order_id", "product", "status", "amount"])
writer.writeheader()
writer.writerows(clean)
print(Path("orders_clean.csv").read_text())order_id,product,status,amount 101,Headphones,DELIVERED,1999 102,Smartwatch,DELIVERED,4999 103,Charger,DELIVERED,1497 104,Smartwatch,CANCELLED,4999 105,Headphones,DELIVERED,1999 106,Laptop Stand,DELIVERED,1299 107,Phone Case,PLACED,1196 107,Phone Case,PLACED,1196
Bad rows (no customer, quantity โtwoโ) were skipped, and order 107 appears twice because the source had a duplicate. Lesson 6 keeps rejected rows with a reason and catches duplicates. Always pass newline="" to open() when using the csv module, or blank lines appear on Windows.
JSON: nested data
import json
with open("data/customers.json", encoding="utf-8") as f:
customers = json.load(f) # JSON array โ list of dicts
asha = customers[0]
print(asha["name"], asha["contact"]["email"]) # nested access
print(customers[1]["contact"]["phone"]) # JSON null โ Python NoneAsha [email protected] None
summary = {"date": "2026-04-01", "orders": len(clean), "revenue": sum(o["amount"] for o in clean)}
with open("summary.json", "w", encoding="utf-8") as f:
json.dump(summary, f, indent=2)
print(Path("summary.json").read_text())
print(json.dumps(summary)) # dict โ JSON text in one line{
"date": "2026-04-01",
"orders": 8,
"revenue": 19184
}
{"date": "2026-04-01", "orders": 8, "revenue": 19184}| JSON | Python |
|---|---|
| object { } | dict |
| array [ ] | list |
| string, number | str, int / float |
| true / false | True / False |
| null | None |
Flattening nested JSON
Databases and CSVs want flat columns, but APIs send nested objects. A small recursive function flattens any depth:
def flatten(record: dict, parent: str = "", sep: str = "_") -> dict:
"""{'contact': {'email': x}} โ {'contact_email': x}"""
flat = {}
for key, value in record.items():
name = f"{parent}{sep}{key}" if parent else key
if isinstance(value, dict):
flat.update(flatten(value, name, sep)) # recursion for nested dicts
else:
flat[name] = value
return flat
print(flatten(customers[0])){'customer_id': 1, 'name': 'Asha', 'city': 'Kolkata', 'contact_email': '[email protected]', 'contact_phone': '98300 00001'}JSON Lines: one record per line
{"event": "page_view", "customer_id": 1, "page": "/headphones", "ts": "2026-04-01T09:00:00"}
{"event": "add_to_cart", "customer_id": 1, "product": "Headphones", "ts": "2026-04-01T09:02:10"}from collections import Counter
counts = Counter()
with open("data/events.jsonl", encoding="utf-8") as f:
for line in f: # one JSON object per line: read one at a time
event = json.loads(line)
counts[event["event"]] += 1
print(counts)Counter({'page_view': 3, 'add_to_cart': 1, 'purchase': 1})Generators: files bigger than memory
List
Builds every value first
All rows in memory at once
50 GB file โ crash
Generator (yield)
Produces one value when asked
One row in memory at a time
50 GB file โ fine
def read_orders(path):
"""Yield one cleaned row at a time instead of loading the whole file."""
with open(path, newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
if row["quantity"].isdigit():
yield int(row["quantity"]) * int(row["price"])
rows = read_orders("data/orders.csv")
print(type(rows))
print(f"Total of valid rows: โน{sum(rows):,}")<class 'generator'> Total of valid rows: โน24,183
import sys
as_list = [n for n in range(1_000_000)]
as_gen = (n for n in range(1_000_000))
print(f"list: {sys.getsizeof(as_list):,} bytes, generator: {sys.getsizeof(as_gen)} bytes")list: 8,448,728 bytes, generator: 192 bytes
A million numbers in a list take about 8 MB; the generator that can produce them takes 192 bytes. A generator can be read only once.
๐ฏ Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1json.load vs json.loads?Fresher+
Q2How would you read a 20 GB CSV file in Python?1โ3 yrs+
Q3What is the difference between a generator and a list?1โ3 yrs+
Q4How do you flatten nested JSON?1โ3 yrs+
Q5Why prefer JSON Lines over a JSON array for pipeline output?3+ yrs+
Key takeaways
- โFiles, CSV and JSON are the bread and butter of extraction.
- โEverything from CSV is text: convert while cleaning.
- โFlatten nested JSON before loading it into tables.
- โGenerators make file size irrelevant. Next: handling errors and bad rows.
Frequently asked questions
Why use 'with open(...)'?
The with block closes the file automatically, even if an error happens inside. Forgetting to close files leaks resources and can leave data unwritten.
Why does csv give me strings for numbers?
CSV is plain text with no types. csv.DictReader returns every value as a string; you convert with int() or float() (or use pandas, which guesses types).
JSON vs JSON Lines?
A JSON file is usually one big array you must load all at once. JSON Lines (.jsonl) has one JSON object per line, so you can process huge files line by line and append new records easily. Pipelines and logs prefer JSON Lines.
What is a generator?
A function that uses yield to produce values one at a time, only when asked. It lets you process a 50 GB file with almost no memory, because only one row exists at a time.
Should I always set encoding='utf-8'?
Yes. The default encoding differs between operating systems, and names like 'Zoรซ' or 'โน' break when the wrong one is used.
๐ง Quick check: files, CSV and JSON
1. csv.DictReader gives each row as...
2. Best format for appending millions of events?
3. A function with 'yield' returns...
4. JSON null becomes which Python value?
Checking your accessโฆ