Python Master Course V2 — 080. Files and Structured Data Capstone
SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · LESSON 080 OF 200 · MODULE 08 — FILES AND STRUCTURED DATA
Files and Structured Data Capstone
Study time: 70–100 minutes. Prerequisites: functions, exceptions, structured data and Lesson 79.
Video
Video not yet available. This section is reserved for a verified lesson video URL or embedded player.
Learning outcomes
Combine parsing, validation and transformation. Explain the concept, trace a sample program, test a boundary condition and implement a small real-world solution.
Detailed explanation
A trustworthy pipeline preserves source records, validates types and produces a repeatable output. Compare input and output counts and document rejected records.
Engineering workflow: define the input and expected output, choose a representation, enforce constraints, implement the smallest useful operation, test success and failure paths, and document the result. Separate data acquisition from transformation and presentation. Avoid hidden global state and irreversible changes during practice.
Production considerations: validate external inputs, preserve recoverable source data, use explicit types, log failures without exposing secrets, and plan for malformed or missing records. As programs grow, modularize code into functions with clear contracts and add automated regression tests.
Understand and apply: Files and Structured Data Capstone
Capstone contract: a small auditable import
Build a CSV-to-JSON stock report that accepts the exact headers item and qty. A product name must be nonblank, and quantity must contain ASCII digits representing a nonnegative integer. This first version preserves duplicate names as separate input records; it does not merge inventory identities. Every data record is either accepted or rejected. A malformed header or broken CSV syntax stops the import because the remaining structure cannot be trusted.
The source remains unchanged. A successful report contains accepted items, explicit rejected-record reasons, input count and total quantity. This makes “no products” different from “all records were invalid.” Record numbers below count CSV records including the header; quoted multiline fields can occupy several physical lines, so do not claim these are always physical line numbers.
Python example
import csv
import json
from io import StringIO
def convert(source):
reader = csv.DictReader(source, strict=True)
if reader.fieldnames != ["item", "qty"]:
raise ValueError("expected headers: item,qty")
accepted, rejected = [], []
for record, row in enumerate(reader, start=2):
if None in row or any(value is None for value in row.values()):
rejected.append({"record": record, "reason": "wrong field count"})
continue
item, qty = row["item"].strip(), row["qty"].strip()
if not item or not qty or not qty.isascii() or not qty.isdecimal():
rejected.append({"record": record, "reason": "invalid item or qty"})
continue
accepted.append({"item": item, "qty": int(qty)})
return {"items": accepted, "rejected": rejected,
"input_count": len(accepted) + len(rejected),
"total_qty": sum(row["qty"] for row in accepted)}
sample = StringIO("""item,qty
Pen,3
Book,0
Bag,-2
,4
""")
report = convert(sample)
print(json.dumps(report, sort_keys=True))
assert report["input_count"] == len(report["items"]) + len(report["rejected"])
Expected output
{"input_count": 4, "items": [{"item": "Pen", "qty": 3}, {"item": "Book", "qty": 0}], "rejected": [{"reason": "invalid item or qty", "record": 4}, {"reason": "invalid item or qty", "record": 5}], "total_qty": 3}
Walk through the two valid records first. Pen contributes three and Book contributes zero, so the accepted quantity is three. The negative quantity fails the digits-only policy; the blank product fails the name policy. Neither becomes a fabricated zero. The conservation check proves every parsed data record has a disposition, although it cannot by itself prove each value was parsed correctly.
Separate conversion from file effects
Pass an open text stream into convert so tests can use StringIO without touching real files. In a command-line wrapper, open the source with UTF-8 and newline="", then write JSON to a separate destination. Reject equal resolved input and output paths. For replaceable reports, write to a temporary file in the destination directory and replace the destination only after serialization and file closing succeed. A rename does not create a backup or guarantee power-loss durability on every filesystem.
The in-memory report is intentionally suitable for small files: both accepted rows and rejection details grow with input size. A truly large-data version should stream accepted records and audit records into separate outputs, carrying only counters and totals in memory. That extension belongs after generators. Avoid calling this small implementation constant-memory.
Acceptance tests should include the supplied four-record fixture, a header-only input yielding empty lists and a zero total, a missing qty cell, an extra cell, quoted names containing commas, incorrect headers and invalid CSV quoting. Compare parsed report objects rather than JSON whitespace. Document the quantity policy and output-path policy in the README before adding more fields.
Runnable Python example
Requires Python 3.10+. Save as lesson80.py, run with python lesson80.py or python3 lesson80.py. Examples use only the standard library.
import csv,json
from io import StringIO
rows=list(csv.DictReader(StringIO("""item,qty
Pen,3
""")))
print(json.dumps({'item':rows[0]['item'],'qty':int(rows[0]['qty'])}))
Expected output:
{"item": "Pen", "qty": 3}
Walkthrough
Read the imports first, then identify the input and the operation that produces the result. Verify the expected output, change one input, predict the new result and rerun. Explain what should happen if the input is empty, invalid or unavailable.
Guided practical project
Scenario: Build a CSV-to-JSON report generator with row-level errors, totals and tests.
- Specify the data schema and constraints in a small requirements table.
- Create a sample dataset with typical, boundary and invalid records.
- Implement separate functions for validation, transformation and reporting.
- Handle expected errors with informative messages.
- Write three automated tests and compare actual with expected results.
- Document execution, assumptions and limitations.
Acceptance criteria: reproducible output, safe handling of invalid data, no silent data loss, and clearly documented assumptions. The project is a guided assignment, not a claim that it has been executed here.
Common mistakes and debugging
- Using the wrong data type or assuming input is always valid.
- Failing to validate keys, fields, constraints or encodings.
- Hiding exceptions with a broad catch rather than identifying the cause.
- Changing important records without backups or transaction planning.
- Testing only normal inputs rather than empty and boundary cases.
When debugging, reproduce with a minimal example, inspect the traceback, compare values to the documented contract and add a regression test.
Practice with explained answers
Make a prediction before opening each answer. Then trace the example and explain the result in your own words.
Why is Book,0 accepted but Bag,-2 rejected?
Zero is permitted nonnegative stock, while the defined digits-only contract excludes a minus sign. This is a deliberate policy rather than a failed int conversion.
How does DictReader expose too many or too few fields?
Extra fields are stored under the None key by default; missing fields receive None values. The validator checks both before accessing or converting values.
What should a header-only file produce?
Zero input records, no items, no rejections and total quantity zero. Headers establish the schema even when there are no data rows.
Why is accepted plus rejected equal to input count useful?
It detects lost records and double counting. It complements value-specific assertions; a program can satisfy the count equation while still computing the wrong quantities.
Does a generator alone make this report constant-memory?
No. Appending every accepted and rejected row to lists still retains all records. Large-data processing requires bounded consumers and streaming output as well as a lazy producer.
Mastery checkpoint
Reproduce the sample, explain each operation, complete the guided project and demonstrate at least three test cases. Learner progress is not account-synchronized by this page.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.