flowchart TD
D1["1. Raw CSV on Disk<br/>raw_hb.csv (UTF-8)"]
R1["2. with open(in_csv, 'r')<br/>csv.DictReader -> rows"]
R2["3. Clean & Aggregate<br/>skip '', 'N/A', '999'"]
W1["4. with open(out_json, 'w')<br/>json.dump(summary, out_f)"]
D2["5. Saved JSON Artifact<br/>flushed & auto-closed"]
D1 --> R1 --> R2 -->|"in_f closed"| W1 -->|"out_f closed"| D2
9 File I/O, CSV/JSON Parsing, and Persistent Data
Chapter Mission: Bridge ephemeral Python memory and durable scientific storage. Master cross-platform
pathlib.Pathobjects, leak-proofwith open(..., encoding="utf-8")context managers, structured tabular parsing withcsv.DictReader/csv.DictWriter, nested metadata persistence withjson.dump/json.load, and cleantempfile.TemporaryDirectory()test sandboxes—turning in-memory scripts into reproducible file pipelines.
Chapter Companion Notebooks (1-to-1 Mirrored in Google Colab)
| Lab Type | Interactive Colab Notebook | Scan (Print) |
|---|---|---|
| Walkthrough | ch09 / 01_walkthrough.ipynb | ![]() |
| Guided To-Dos | ch09 / 02_guided_todos.ipynb | ![]() |
| Coding Exam | ch09 / 03_coding_exam.ipynb | ![]() |
Learning Objectives
By the end of this chapter, you will be able to:
- Construct operating-system-independent file paths with
pathlib.Pathand isolate scratch file experiments cleanly insidetempfile.TemporaryDirectory(). - Read and write plain-text research logs safely using
with open(..., encoding="utf-8")context managers and distinguish"r","w", and"a"file modes. - Parse and export structured clinical tables with
csv.DictReaderandcsv.DictWriterusingnewline="", converting string cells explicitly to numbers after skipping missing sentinels. - Serialize and reload nested study metadata, protocol cutoffs, and aggregated summaries with
json.dump(..., indent=2)andjson.load(...). - Diagnose and prevent the three classic file-pipeline exceptions:
FileNotFoundError,json.JSONDecodeError, andio.UnsupportedOperation. - Compose multi-file CSV-to-CSV, CSV-to-JSON, and multi-JSON aggregation pipelines that never mutate raw source registries.
9.1 Stage 1 — First-Principles Intuition: Volatile RAM vs. the Locked Archive Cabinet
Every variable you built in Chapters 1 through 8—lists of hemoglobin readings, dictionaries of outbreak counts, sets of unique districts—lived in RAM (Random Access Memory). RAM is blazingly fast, yet completely volatile: the moment your Google Colab runtime disconnects or your laptop reboots, every in-memory object vanishes without a trace.
Reproducible science requires persistence: saving cleaned cohorts, summary statistics, and study metadata onto disk so collaborators, statistical packages, and peer reviewers can inspect and verify every step.
Working with files in Python works just like borrowing records from a locked hospital archive room:
- Archive Street Address (
pathlib.Path): Rather than gluing folder names with brittle backslashes ("data\\raw.csv") that fail across Windows, macOS, and Linux,Path(folder) / "raw.csv"builds clean, portable file paths automatically. - Self-Locking Checkout Gate (
with open(...)): Opening a file checks out an operating-system handle. Wrapping it inside awithcontext manager guarantees Python flushes every buffered byte to disk and locks the cabinet again—even if an exception crashes halfway through your loop. - Universal Ink Standard (
encoding="utf-8"): Always declareencoding="utf-8"explicitly so clinical symbols (°C,μg/L) and international place names survive identically on every researcher’s computer. - Right Cabinet for the Right Data (Text vs. CSV vs. JSON): Use plain text (
.txt) for chronological shift logs, CSV (.csv) for flat row-by-column patient registries, and JSON (.json) for nested hierarchies (study metadata, cutoffs, grouped summaries).
9.1.1 Golden Rule of Non-Destructive Research Pipelines
Never overwrite your raw field survey file! Treat raw files as read-only evidence ("r"), transform them in Python memory, and write cleaned cohorts or aggregated summaries to new derived files ("w"). That way, if you discover a new sentinel code next month, you can re-run the pipeline from scratch with zero data loss.
9.2 Stage 2 — Visual Mental Model: Context-Manager & File-Pipeline Lifecycle
Follow the exact lifecycle of a clean CSV-to-JSON surveillance pipeline from raw disk file through Python’s context managers to persistent summary output:
Notice the two most important architectural safeguards in this diagram:
- Automatic Resource Cleanup: Each
withblock guarantees its file handle closes immediately upon block exit—whether the block finishes normally or raises an error. - Explicit Type Boundary: Files on disk store only text characters (bytes).
csv.DictReaderalways delivers strings ("10.4"), which your code converts explicitly withfloat()orint(). By contrast,json.load()automatically restores JSON numbers (11.0), booleans (true\(\rightarrow\)True), lists, and nested dicts.
tempfile.TemporaryDirectory() in Demos & Tests
Every walkthrough example and sharukh-tutor verifier in this chapter runs inside with tempfile.TemporaryDirectory() as tmp:. Python creates a private scratch folder for the duration of the block and deletes it automatically on exit—keeping your project repository and Google Colab workspace completely spotless.
9.3 Stage 3 — Line-by-Line Code Walkthrough & Error Anatomy
Open part_02_data_structures_algorithms/ch09_files_csv_json/01_walkthrough.ipynb in Colab and execute every cell alongside the dissections below.
9.3.1 Modern Paths (pathlib.Path) & Safe Text I/O (with open)
from pathlib import Path
import tempfile
with tempfile.TemporaryDirectory() as tmp:
log_path = Path(tmp) / "clinic_shift.txt"
entries = [
"08:15 | Dhaka-North | Temp 38.4°C",
"09:00 | Sylhet-East | Hb 10.6 g/dL",
"10:30 | Khulna-West | Routine ANC",
]
with open(log_path, "w", encoding="utf-8") as out_f:
for entry in entries:
out_f.write(f"{entry}\n")
print("File name:", log_path.name, "| Exists:", log_path.exists())
with open(log_path, "r", encoding="utf-8") as in_f:
for line_no, line in enumerate(in_f, start=1):
print(f"Line {line_no}: {line.strip()}")Expected Output:
Key mechanics to inspect closely:
Path(tmp) / "clinic_shift.txt":pathlib.Pathoverloads the/operator to join directories and filenames cleanly on every operating system.- Explicit
\non writes: Unlikeprint(),out_f.write(...)does not append a newline automatically; omitting\nwould glue all three entries onto one line. - Streaming line reads: Iterating
for line in in_f:reads one line at a time using constant memory, andline.strip()removes the trailing\n.
9.3.2 Structured Tables with csv.DictWriter & csv.DictReader
Splitting CSV rows manually with line.split(",") breaks the moment a clinic address or diagnosis note contains a comma inside quotes ("Dhaka, North"). Always use Python’s standard-library csv module instead:
import csv
from pathlib import Path
import tempfile
records = [
{"patient_id": "P001", "district": "Dhaka", "hb_g_dl": "10.4"},
{"patient_id": "P002", "district": "Sylhet", "hb_g_dl": "12.1"},
{"patient_id": "P003", "district": "Khulna", "hb_g_dl": "9.8"},
]
with tempfile.TemporaryDirectory() as tmp:
csv_path = Path(tmp) / "mch_cohort.csv"
fields = ["patient_id", "district", "hb_g_dl"]
with open(csv_path, "w", encoding="utf-8", newline="") as out_f:
writer = csv.DictWriter(out_f, fieldnames=fields)
writer.writeheader()
writer.writerows(records)
with open(csv_path, "r", encoding="utf-8", newline="") as in_f:
loaded = list(csv.DictReader(in_f))
hb_vals = [float(row["hb_g_dl"]) for row in loaded]
print("Rows loaded:", len(loaded))
print("First row:", loaded[0])
print("Mean Hb (g/dL):", round(sum(hb_vals) / len(hb_vals), 2))Expected Output:
csv Habits
- Always pass
newline=""toopen(): Bothcsv.DictReaderandcsv.DictWritermanage line endings internally. Omittingnewline=""inserts extra blank lines between every row on Windows! - Materialize before closing:
csv.DictReader(in_f)is a streaming iterator. If you need rows after thewithblock ends, wrap it inlist(csv.DictReader(in_f))while the file is still open.
9.3.3 Persisting Nested Metadata with json.dump & json.load
Flat CSV tables cannot naturally represent nested dictionaries, lists of study sites, or mixed booleans and floats. JSON (JavaScript Object Notation) preserves that full nested hierarchy cleanly across Python, R, JavaScript, and web APIs:
import json
from pathlib import Path
import tempfile
study_meta = {
"study_id": "MCH-BD-2026",
"sites": ["Dhaka", "Sylhet", "Khulna"],
"cutoffs": {"anemia_g_dl": 11.0, "fever_c": 38.0},
"active": True,
}
with tempfile.TemporaryDirectory() as tmp:
json_path = Path(tmp) / "study_meta.json"
with open(json_path, "w", encoding="utf-8") as out_f:
json.dump(study_meta, out_f, indent=2)
with open(json_path, "r", encoding="utf-8") as in_f:
restored = json.load(in_f)
print("Study ID:", restored["study_id"])
print("Anemia cutoff:", restored["cutoffs"]["anemia_g_dl"])
print("Protocol version:", restored.get("version", "v1.0"))Expected Output:
Notice the crucial naming pair in Python’s json module:
json.dump(obj, file_handle)/json.load(file_handle)(no trailings): read/write directly with an open file handle.json.dumps(obj)/json.loads(text_str)(with trailingsfor string): convert between Python objects and in-memory JSON strings.
9.3.4 Break It On Purpose! (File I/O & JSON Error Anatomy)
Python’s Traceback:
Diagnosis: Opening a file in read mode ("r") requires the file to already exist on disk. A single misspelled filename or wrong working folder triggers FileNotFoundError.
Fix: Verify missing_path.exists() or inspect missing_path.resolve() to confirm the exact path before opening.
Python’s Traceback:
Diagnosis: JSON syntax is strict: missing values, trailing commas ({"a": 1,}), or Python single quotes ({'a': 1}) make json.load() reject the file at the exact line and column of the syntax error.
Fix: Always produce JSON files with json.dump(...) rather than hand-building strings or calling str(my_dict).
Python’s Traceback:
Diagnosis: The file was opened in read-only mode ("r"), so calling f.write(...) violates the handle’s permissions and raises io.UnsupportedOperation.
Fix: Open with "w" (create/overwrite) or "a" (append to end) whenever you intend to write bytes to disk.
9.4 Stage 4 — The Researcher’s Problem-Structuring Blueprint
Scenario: An Upazila Health Complex exports a messy daily antenatal CSV containing inconsistent district labels (" dhaka ", "DHAKA", "sylhet") and missing hemoglobin sentinels ("", "N/A", "999"). Build a reusable function csv_to_district_hb_json(in_csv, out_json) that reads the raw CSV, normalizes districts, computes each district’s valid mean hemoglobin rounded to 2 decimal places, writes an indented JSON summary to out_json, and returns that summary dictionary.
9.4.1 Blueprint (Completed on Paper Before Coding)
- Input & Output Contract:
- Input:
in_csv(Pathorstr) with columnsid,district,hb_g_dl. - Output: Indented UTF-8 JSON file at
out_json+ returneddict[str, float].
- Input:
- Edge Cases & Traps:
- Every
csv.DictReadervalue is astr—skip"","N/A", and"999"before callingfloat(...). - Normalize
row["district"].strip().title()so" dhaka "and"Dhaka"merge into one"Dhaka"key instead of splitting into duplicate entries. - Skip invalid rows before inserting a district key into
groupedso an all-invalid district never triggersZeroDivisionError.
- Every
- Step-by-Step Algorithm:
- Initialize
grouped = {}. - Stream
in_csvwithcsv.DictReader; striphb_g_dland skip sentinel values. - Normalize district name and append
float(raw_hb)viagrouped.setdefault(district, []).append(...). - Compute rounded per-district means with a dict comprehension.
- Save with
json.dump(summary, out_f, indent=2)and returnsummary.
- Initialize
- Verification Plan (Hand Check):
- Dhaka valid values:
10.4,11.6(skipping999) \(\rightarrow\) \((10.4 + 11.6) / 2 = 11.0\). - Sylhet valid values:
12.2,11.4(skippingN/A) \(\rightarrow\) \((12.2 + 11.4) / 2 = 11.8\).
- Dhaka valid values:
9.4.2 Clean Python Implementation (Verbatim in 01_walkthrough.ipynb)
import csv
import json
from pathlib import Path
import tempfile
def csv_to_district_hb_json(in_csv, out_json):
"""Aggregate valid Hb by normalized district and save JSON."""
grouped = {}
with open(in_csv, "r", encoding="utf-8", newline="") as in_f:
for row in csv.DictReader(in_f):
raw_hb = row["hb_g_dl"].strip()
if raw_hb in ("", "N/A", "999"):
continue
district = row["district"].strip().title()
grouped.setdefault(district, []).append(float(raw_hb))
summary = {
dist: round(sum(vals) / len(vals), 2)
for dist, vals in grouped.items()
}
with open(out_json, "w", encoding="utf-8") as out_f:
json.dump(summary, out_f, indent=2)
return summary
with tempfile.TemporaryDirectory() as tmp:
raw_csv = Path(tmp) / "raw_hb.csv"
out_json = Path(tmp) / "district_hb.json"
raw_csv.write_text(
"id,district,hb_g_dl\n"
"M1, dhaka ,10.4\n"
"M2,DHAKA,999\n"
"M3,Dhaka,11.6\n"
"M4,sylhet,12.2\n"
"M5,Sylhet,N/A\n"
"M6,SYLHET,11.4\n",
encoding="utf-8",
)
report = csv_to_district_hb_json(raw_csv, out_json)
print("Returned summary:", report)
print("Saved JSON:\n" + out_json.read_text(encoding="utf-8"))Output:
9.5 Stage 5 — Guided “To-Do” Practice Labs
Open part_02_data_structures_algorithms/ch09_files_csv_json/02_guided_todos.ipynb in Google Colab, run Step 0 to activate sharukh-tutor, and build all six file-handling functions below. Each tutor.check(...) test creates clean temporary files inside tempfile.TemporaryDirectory() and passes Path objects directly to your function:
- To-Do 9.1 (Warm-Up —
count_nonempty_lines(filepath)): Read a UTF-8 text file viawith open(...)and return theintcount of lines whereline.strip()is non-empty. - To-Do 9.2 (UTF-8 Text Writer —
write_clinic_log(filepath, entries)): Write each entry inentrieson its own line in UTF-8 (mode="w") and return the integer count written. - To-Do 9.3 (CSV Reader —
read_csv_as_dicts(csv_path)): Read a CSV file viacsv.DictReader(encoding="utf-8",newline="") and return a materializedlist[dict]. - To-Do 9.4 (Sentinel-Safe CSV Mean —
mean_csv_column(csv_path, col_name)): Read columncol_nameviacsv.DictReader, skip"","N/A", and"999", and return the mean rounded to 2 decimal places (orNoneif no valid values exist). - To-Do 9.5 (JSON Writer —
save_study_metadata(json_path, metadata_dict)): Persistmetadata_dicttojson_pathas valid, indented UTF-8 JSON (indent=2). - To-Do 9.6 (Safe JSON Loader —
load_json_key(json_path, key, default=None)): Load a JSON dictionary fromjson_pathand returndata.get(key, default)without crashing on missing keys or clobbering falsy values (0,False).
9.6 Stage 6 — Concept & Execution Trace Test (No Computer Allowed!)
Test your understanding on paper before checking Stage 8:
Context Manager Safety: Why is
with open(path, "w", encoding="utf-8") as f:strictly safer than callingf = open(path, "w")followed byf.close()at the bottom of a function?Mode Difference (
"w"vs."a"): A clinic script opensdaily_log.txtthat already has 10 lines using mode"w"and writes 2 lines. How many lines are indaily_log.txtafterward? What if it used mode"a"instead?Path Joining: Why should you write
Path("data") / "raw" / "mch.csv"instead of"data\\raw\\mch.csv"?CSV Cell Types: In a CSV with row
P001,Dhaka,10.8, what Python data type isrow["hb_g_dl"]right aftercsv.DictReaderyieldsrow? What happens if you runrow["hb_g_dl"] < 11.0without converting first?Closed-File Iterator Bug: What error happens if you run this snippet?
newline=""Purpose: Why does Python’s officialcsvdocumentation requirenewline=""insideopen(...)for bothDictReaderandDictWriter?json.dumpvs.json.dumps: Which function writes directly to an open file handle, and which returns an in-memory JSON string?Invalid JSON Serialization Trap: Why does
f.write(str({"active": True, "site": "Dhaka"}))produce a file that crashesjson.load()?Falsy Value Trap: Suppose
config.jsoncontains{"missing_count": 0}. What doesdata.get("missing_count") or 99return versusdata.get("missing_count", 99)?Temporary Sandbox Cleanup: If code inside
with tempfile.TemporaryDirectory() as tmp:raises aValueError, does the temporary directory get left behind on disk or cleaned up automatically?
9.7 Stage 7 — Chapter 9 Hands-On Coding Exam (100 Points)
Open part_02_data_structures_algorithms/ch09_files_csv_json/03_coding_exam.ipynb, implement all three persistent file-pipeline functions, and run tutor.check_exam("ch09", exam_submissions) to earn your Chapter 9 score out of 100 points.
9.7.1 Exam Task 9.1 (30 Points): Filter Urgent Triage Rows to CSV
Write filter_urgent_to_csv(in_csv, out_csv) to export priority clinical referrals:
- Read
in_csvwithcsv.DictReader(encoding="utf-8",newline=""). - Write to
out_csvusingcsv.DictWriter(out_f, fieldnames=reader.fieldnames)and always callwriter.writeheader()so even 0-match exports preserve valid CSV headers. - Write only rows where
row["triage_priority"] == "Urgent". - Return the
intcount of Urgent rows written.
9.7.2 Exam Task 9.2 (35 Points): Messy MCH CSV to Per-Residence JSON Summary
Write summarize_mch_csv_to_json(in_csv, out_json) to aggregate antenatal care visits from a messy field export:
- Read
in_csvcontainingresidence(e.g.,"rural"," Rural ","URBAN") andanc_visits(with missing sentinels"999"and""). - Skip rows where
anc_visits.strip()is"","999", or"N/A". - Normalize
residencevia.strip().title()and compute each group’s valid meananc_visitsrounded to 2 decimal places. - Write the summary dictionary to
out_jsonas indented UTF-8 JSON (indent=2) and return that dictionary.
9.7.3 Exam Task 9.3 (35 Points): Merge Daily JSON Disease Reports
Write merge_daily_json_reports(json_paths) to combine multi-day outbreak counts across separate files:
- Accept a list of
Path(orstr) objects, each pointing to a UTF-8 JSON file mappingdisease -> count. - Load every JSON file and sum counts for each disease across all files into a single combined dictionary.
- Return the combined dictionary (returning
{}whenjson_pathsis empty).
9.8 Stage 8 — Complete Annotated Solutions & Debugging Post-Mortem
9.8.1 A. Concept & Execution Trace Test Key
with open(...)guarantees the file handle is flushed and closed automatically when leaving the block, even if an exception interrupts execution before the end of the function.- Mode
"w"truncates and overwrites the file, leaving 2 lines. Mode"a"appends to the end, leaving 12 lines. pathlib.Pathwith/produces portable paths across Windows, macOS, and Linux, whereas hardcoded backslashes fail on Unix/Colab systems and risk escape-sequence bugs (\t,\n).row["hb_g_dl"]is astr("10.8"). Comparing"10.8" < 11.0directly raisesTypeError: '<' not supported between instances of 'str' and 'float'.- Raises
ValueError: I/O operation on closed file, becauselist(reader)tried to read fromfafter exiting thewithblock closedf. - The
csvmodule handles universal newline translation and embedded newlines inside quoted fields itself; passingnewline=""prevents Python from double-translating\r\ninto extra blank rows on Windows. json.dump(obj, f)writes to an open file handle;json.dumps(obj)returns a JSON-formattedstrin memory.str(...)outputs Python literal syntax—single quotes ('active') and capitalizedTrue—whereas the JSON standard strictly requires double quotes ("active") and lowercasetrue.data.get("missing_count") or 99treats0as falsy and wrongly returns99;data.get("missing_count", 99)checks key membership and accurately returns0.- It is cleaned up automatically—
TemporaryDirectoryis a context manager whose__exit__method deletes the scratch folder even when an exception occurs.
9.8.2 B. Annotated Solutions — Guided To-Dos (Mirrored in 02_guided_todos_SOLUTION.ipynb)
import csv
import json
# To-Do 9.1
def count_nonempty_lines(filepath):
"""Return int count of lines whose stripped text is non-empty."""
count = 0
with open(filepath, "r", encoding="utf-8") as f:
for line in f:
if line.strip():
count += 1
return count
# To-Do 9.2
def write_clinic_log(filepath, entries):
"""Write each entry on its own UTF-8 line and return count."""
with open(filepath, "w", encoding="utf-8") as f:
for entry in entries:
f.write(f"{entry}\n")
return len(entries)
# To-Do 9.3
def read_csv_as_dicts(csv_path):
"""Load a CSV file via csv.DictReader and return list[dict]."""
with open(csv_path, "r", encoding="utf-8", newline="") as f:
return list(csv.DictReader(f))
# To-Do 9.4
def mean_csv_column(csv_path, col_name):
"""Return mean of col_name skipping '', 'N/A', '999', or None."""
values = []
with open(csv_path, "r", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
raw = row[col_name].strip()
if raw in ("", "N/A", "999"):
continue
values.append(float(raw))
if not values:
return None
return round(sum(values) / len(values), 2)
# To-Do 9.5
def save_study_metadata(json_path, metadata_dict):
"""Serialize metadata_dict to indented UTF-8 JSON at json_path."""
with open(json_path, "w", encoding="utf-8") as f:
json.dump(metadata_dict, f, indent=2)
# To-Do 9.6
def load_json_key(json_path, key, default=None):
"""Load JSON dict from json_path and return data.get(key, default)."""
with open(json_path, "r", encoding="utf-8") as f:
data = json.load(f)
return data.get(key, default)9.8.3 C. Annotated Solutions — Chapter 9 Coding Exam (Mirrored in 03_coding_exam_SOLUTION.ipynb)
import csv
import json
# Exam Task 9.1 (30 pts)
def filter_urgent_to_csv(in_csv, out_csv):
"""Write Urgent rows to out_csv with header and return count."""
count = 0
with open(in_csv, "r", encoding="utf-8", newline="") as in_f, \
open(out_csv, "w", encoding="utf-8", newline="") as out_f:
reader = csv.DictReader(in_f)
writer = csv.DictWriter(out_f, fieldnames=reader.fieldnames)
writer.writeheader()
for row in reader:
if row["triage_priority"] == "Urgent":
writer.writerow(row)
count += 1
return count
# Exam Task 9.2 (35 pts)
def summarize_mch_csv_to_json(in_csv, out_json):
"""Compute per-residence mean ANC visits, save JSON, return dict."""
grouped = {}
with open(in_csv, "r", encoding="utf-8", newline="") as in_f:
for row in csv.DictReader(in_f):
raw_anc = row["anc_visits"].strip()
if raw_anc in ("", "999", "N/A"):
continue
residence = row["residence"].strip().title()
grouped.setdefault(residence, []).append(float(raw_anc))
summary = {
res: round(sum(vals) / len(vals), 2)
for res, vals in grouped.items()
}
with open(out_json, "w", encoding="utf-8") as out_f:
json.dump(summary, out_f, indent=2)
return summary
# Exam Task 9.3 (35 pts)
def merge_daily_json_reports(json_paths):
"""Load daily disease->count JSON files and return summed totals."""
totals = {}
for path in json_paths:
with open(path, "r", encoding="utf-8") as f:
report = json.load(f)
for disease, count in report.items():
totals[disease] = totals.get(disease, 0) + count
return totals9.8.4 D. Debugging Post-Mortem: Top 3 Chapter 9 Failure Modes
- Treating CSV Numbers as Floats Before Cleaning: Because
csv.DictReaderreturns every cell as a string, callingfloat(row["anc_visits"])immediately crashes withValueErroron""or"N/A", or silently includes999.0in your published mean. Always strip, filter sentinels ("","N/A","999"), and then cast withfloat(). - Reading After the
withBlock Closes or Skippingwriteheader(): Returningcsv.DictReader(f)directly instead oflist(csv.DictReader(f))fails the moment thewithblock exits; likewise, omittingwriter.writeheader()leaves your exported CSV without column headers so downstream tools misread row 1 as column names. - Writing Python
str(dict)Instead ofjson.dump(): Printing or writingstr(my_dict)produces single quotes andTrue/False, which breaks every JSON parser withjson.JSONDecodeError. Always serialize withjson.dump(obj, f, indent=2)and retrieve optional keys withdata.get(key, default).
You can now move seamlessly between raw disk files, structured CSV registries, and nested JSON summaries without leaving stray temporary files behind. In the next chapter, we combine these persistent file workflows with defensive exception handling, assertions, and reusable scientific modules.


