Skip to main content
6 day streak
Skip to lesson
CareerPetalPython field guide
Loading progress...
Course contents
PYTHON FIELD GUIDE

Course contents 72 topics / 15 parts

Full course overviewOriginal coding practice / separate server checks

Essentials first, then internals and engineering trade-offs.

LESSON 20 / FILES AND STANDARD LIBRARY

Paths, CSV and streaming file pipelines

Parse real records without accidental truncation or unbounded reads.

IntermediateTutorial 14 min core+12 min deep divePython 3.11+ / 2026-10-27
Saved work unavailable

Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.

Before you start

Learners who can read small Python functions and want to apply the listed foundations.

Explore the connected curriculum and preparation map

Lesson content version 2026-10-27. Suggested core budget: 14 minutes; optional deep dive: 12 more minutes. These are reading/practice estimates, not a timed test.

Suggested preparation and repair routes

If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.

Actual runtime and local-lab boundaries

Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.

Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.

Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.

YOU WILL BE ABLE TO
  • Explain paths describe locations
  • Apply csv is a format, not a split
  • Reason about safe output replacement
01

Paths describe locations

A path describes a location. A pure path manipulates location names without opening, creating or checking any real file.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Joining strings with hand-written separators is fragile. A path object makes the base, filename and suffix visible. Learn these naming operations before any filesystem side effect. This example chooses a pure POSIX model so output does not depend on the host.

Words you will see

Absolute path
A location name starting at a filesystem root.
Relative path
A location interpreted from a base, often the process working directory.
Pure path
A path representation that performs naming operations without filesystem access.

Join names without inventing file access

The / operator joins the base with daily.csv; it does not divide numbers or create a file. name returns the last component and suffix returns its final extension. as_posix displays forward-slash notation for this explicitly POSIX teaching model. PureWindowsPath is available when the names themselves use Windows rules.

Path, unlike PurePosixPath, also offers real access operations such as open and exists. A relative Path('daily.csv') uses the working directory when accessed, not automatically the script's folder. Keep the chosen base explicit rather than depending on how a launcher started the program.

A joined path is not a permission check

A user-supplied absolute component can replace the base; .. components can describe movement toward a parent. Pure paths do not resolve symbolic links or prove containment. A real upload boundary needs an allowed-name policy and platform-aware filesystem controls, not just string concatenation or a prefix test.

This browser program is naming only. /workspace/reports is a conceptual base, not an existing host directory. No mkdir, exists or file read is attempted, and output is not evidence that a file exists. In a real lab, supply the directory deliberately and handle missing files and permission errors visibly.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. from pathlib import PurePosixPath

    Choose a host-independent POSIX naming model.

  2. base = PurePosixPath("/workspace/reports")

    Represent an absolute base without opening it.

  3. target = base / "daily.csv"

    Join one relative filename.

  4. print(target.as_posix())

    Display the joined spelling, not a successful write receipt.

  5. print(target.name, target.suffix)

    Read daily.csv and .csv from the final component.

pathlib.Path separates path operations from string concatenation. Use an explicit base directory and encoding; never trust an uploaded filename as an unrestricted filesystem path. A relative path is interpreted from the process working directory, which may differ from the script's folder.

Conceptual path composition, not a filesystem inspection

Conceptual reasoning steps for the original example, not a live trace of your edited Python.

  1. Explicit base/workspace/reports is a represented POSIX location.
  2. Relative componentdaily.csv joins to that base using /.
  3. Joined name/workspace/reports/daily.csv describes a location; no file is created.
Predict before you run

Does constructing target create daily.csv?

Describe an explicit report locationPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Change the output format name.

Try: Replace "daily.csv" with "daily.json".

The displayed location ends in daily.json and suffix becomes .json.

Inspect a relative path.

Try: Change the base to PurePosixPath("reports").

The output loses its leading slash; no working-directory resolution is performed.

Before you move on

Would base / '/outside.csv' remain under reports in this POSIX model?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

No. An absolute right operand replaces the earlier base. Reject absolute names and unwanted components at the boundary; joining alone is not confinement.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
02

CSV is a format, not a split

CSV represents table rows as text with quoting rules. A CSV parser recognises field boundaries even when a value contains a comma or newline.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A comma inside a person's display name must not create an extra column. Use csv.DictReader when a header names each field. Start with strings and dictionaries; the reader gives structure but does not know your application types.

Words you will see

Delimiter
The character separating fields, normally a comma here.
Quoted field
A field surrounded by quote characters so delimiters or newlines may belong to its value.
Header
A row that supplies column names.

Let the parser own the boundary rules

DictReader consumes name,minutes as headers. The next logical record maps those names to strings. Quotes around Ada, A. group the comma with the name, so row['minutes'] is still '15'. A logical record may span physical lines when a field contains a quoted newline.

Splitting each line on commas would produce too many pieces. Splitting into lines first also breaks multiline quoted fields. Pass a text stream to csv and let it decide where records end. For real text files use open(..., newline='', encoding='utf-8'); newline='' lets csv handle newline conventions.

Parsing is only one part of a table contract

The reader does not infer integer types. int('15') is an explicit later conversion and can raise ValueError for bad text. Missing or extra columns and duplicate headers need a policy; DictReader's permissive defaults are not schema validation. Validate headers and row widths when a report must be reliable.

The fixture uses StringIO, so it reads neither a host file nor an upload. For a known semicolon format set delimiter=';' rather than guessing from one convenient sample. Use csv.writer to produce CSV safely; joining with commas repeats the same quoting mistake in reverse.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. with StringIO(text, newline="") as stream:

    Provide the supplied table text with CSV-aware newline handling.

  2. rows = csv.DictReader(stream)

    Prepare a reader whose first row supplies dictionary keys.

  3. row = next(rows)

    Read the first data record, preserving the quoted comma.

  4. print(row["name"])

    Display Ada, A. as one field.

  5. print(row["minutes"], type(row["minutes"]).__name__)

    Show 15 and str; no numeric conversion happened.

Quoted fields may contain commas and newlines, so use csv rather than splitting on commas. When opening real files for csv, use newline='' and an explicit text encoding. Iterate records, validate required fields and decide how malformed rows are reported.

Predict before you run

What type does DictReader give the minutes field?

Read a quoted fieldPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Read another row.

Try: Add Lin,0\n to text and replace row = next(rows) with row = list(rows)[1].

The output becomes Lin and 0 str; zero remains text.

Compare the broken alternative.

Try: Add print(text.splitlines()[1].split(",")) before with.

The naive split shows three pieces, unlike the parser's two fields.

Before you move on

If a quoted note contains a newline, must it become two records?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

No. csv reads until the quoted field closes and returns one logical record. Manual line splitting would lose that structure.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
03

Parse quoted CSV records

A record pipeline reads, validates and accumulates rows in order. Keeping only a total avoids building a second collection of every record.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A report total usually needs one running sum, not a list of every parsed row. Compose the parser and conversion deliberately. This original example assumes a valid small fixture; the guided exercise adds the missing validation contract.

Words you will see

Pipeline
Stages that pass one record from reading through transformation to a result.
Materialise
Build and retain a complete collection instead of consuming records incrementally.
Conversion
Turn a representation such as '15' into a value such as 15.

Follow the row, not just the final number

DictReader reads the header, then yields dictionaries. The first minutes string is '15'; int makes 15 and total becomes 15. The second string is '20'; adding it makes 35. A duplicate row would contribute again because each record represents a separate observation.

The loop does not call list(rows), so it does not retain all decoded dictionaries. StringIO still wraps an already allocated text fixture; this is browser-local parsing, not proof that the whole application streams from disk. For large real sources, pass the actual managed stream rather than first calling read on the entire file.

Make invalid-row behavior explicit

An absent minutes header can lead to KeyError. A missing cell may be None, and a nonnumeric cell fails conversion. The original demonstration lets errors propagate instead of converting them into zero. A production report should attach a useful record number and reject bad units or state a documented partial-result policy.

Iteration is preferable to a separate list for a simple sum. Materialisation is appropriate when repeated random access or sorting really is required. Do not sort solely to compute a total: it adds memory and work and may obscure the original diagnostic order.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. rows = csv.DictReader(StringIO(text))

    Wrap the supplied text and prepare header-based records.

  2. total = 0

    Start with an integer total of zero.

  3. for row in rows:

    Visit two data records, not the header.

  4. total += int(row['minutes'])

    Convert each minutes string and add 15 then 20.

  5. print(total)

    Print 35 after the reader is exhausted.

DictReader understands the quoted comma in a name and produces one record per row without materialising a separate list.

Predict before you run

What happens to the comma in Ada's name?

Parse quoted CSV recordsPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Add a repeated observation.

Try: Append Lin,20\n to the fixture.

The total becomes 55; no row is deduplicated.

Try a bad numeric field.

Try: Change the second row's 20 to twenty.

int raises ValueError. A failing run has no actual successful total.

Before you move on

A third record repeats Lin,20. Should this unchanged pipeline still print 35?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

No. It prints 55. Each row contributes independently; recognising a repeated name does not prove a duplicate observation.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
DETAILED WALKTHROUGH / NOT JUST A SUMMARY

Where this idea earns its place

CSV imports combine filesystem safety, format parsing and record validation. A valid path does not imply a trusted file, and a valid CSV row does not imply valid business data. Keep those responsibilities separate so a quoted comma is not mistaken for a security problem and a negative duration is not mistaken for a parser failure.

Follow the mechanism step by step

Path resolves a location according to the working directory and platform rules. csv.DictReader reads the header and applies CSV quoting rules to records. A quoted field can contain delimiters or newlines, so line splitting and comma splitting cannot reconstruct every valid record. DictReader then returns strings that still require domain conversion.

Work through a concrete application

Declare required columns before processing rows. For each row, normalise only the fields whose contracts allow it, parse units and validate ranges. Include row context in an actionable error without logging private raw records. Aggregate one row at a time and format output only after the chosen success or partial-failure policy is known.

Failure cases and misleading shortcuts

An unexpected extra column, duplicate header or missing field needs a stated policy. Silent coercion can turn a malformed amount into zero and corrupt totals. A filename supplied by an upload may include traversal components; joining it with a base string does not automatically confine access to the intended directory.

Cost, ownership and alternatives

Streaming bounds retained input rows but not all aggregation state. Millions of distinct grouping keys can still exhaust memory. Parsing cost also depends on field length and quoting, not only row count. Prefer a database or partitioned report when the output cardinality cannot fit the approved memory budget.

Verify the contract

Test quoted commas, quoted newlines, different line endings, missing headers, invalid numeric fields, empty files and oversized records. Use a StringIO fixture for parser tests and separate temporary-file tests for encoding/path behaviour. Check that the input file remains unchanged and that failed output does not replace a previously valid report.

Transfer question: Can a streaming CSV parser guarantee constant memory for every group-by report?

No. It can avoid retaining all rows while the group-by mapping still grows with distinct keys. Bound the number and size of groups, spill to external storage or change the reporting strategy. Include parser buffers and error samples in the memory model.

RECALL BEFORE YOU SCROLL

Can you explain it?

Try from memory. Feedback stays on this page and does not award judged progress.

Why not parse CSV with line.split(',')?
TRANSFER THE IDEA

Rebuild: Parse quoted CSV records

Without copying the worked code, reproduce its observable contract: DictReader understands the quoted comma in a name and produces one record per row without materialising a separate list. Then change one boundary input and explain the result.

Your practice starterPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

MAKE THE RULE WORK ON NEW INPUTS

Guided practice and transfer

These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.

A short function primer before you begin

def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.

return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.

Return a value, do not only print itPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

GUIDED PRACTICE

Guided: validate a CSV total

Sum a strict two-column CSV without breaking quoted names.

The contract

  • Input text must have exactly the header name,minutes in that order. Each logical data row has exactly two fields; name may be empty.
  • After stripping surrounding whitespace, minutes must contain one or more ASCII digits 0-9. Return their integer sum; repeats count, header-only returns 0. Reject missing/extra cells, wrong header or bad minutes with ValueError.
  • Use csv with strict=True, in-memory streams only; no mutation or retained state. Quoted newlines/commas are supported.
Guided: validate a CSV totalPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Inspect 6 public checks

Transparent local learning checks, not exhaustive or tamper-proof grading.

  1. quoted
    assert csv_minutes('name,minutes\n"Ada, A.",15\nLin,20\n') == 35
  2. header only
    assert csv_minutes("name,minutes\n") == 0
  3. duplicates and zero
    assert csv_minutes("name,minutes\nA,0\nA,2\nA,2\n") == 4
  4. multiline
    assert csv_minutes('name,minutes\n"Ada\nA.", 02 \n') == 2
  5. invalid inputs
    for text in ("", "minutes,name\n2,A", "name,minutes\nA", "name,minutes\nA,2,x", "name,minutes\nA,-1", "name,minutes\nA,٢", "name,minutes\nA,", 'name,minutes\n"A,2'):
        try:
            csv_minutes(text)
        except ValueError:
            continue
        raise AssertionError("Invalid CSV accepted")
  6. caller and independence
    text = "name,minutes\nA,3\n"
    assert csv_minutes(text) == 3 and text == "name,minutes\nA,3\n" and csv_minutes("name,minutes\n") == 0 and csv_minutes(text) == 3
    Why not simply call int on every minutes cell?

    int accepts signs and some Unicode digits outside this report's explicit ASCII contract. For b characters the bounded fixture requires O(b) parsing work and input/stream storage, plus one row and a total.

    GUIDED PRACTICE

    Guided: export rows faithfully

    Produce deterministic CSV and preserve the caller's row lists.

    The contract

    • Input is a list of [name, minutes] rows, with name a string and minutes a nonnegative int. Inputs already satisfy this contract.
    • Return CSV text with header name,minutes, comma delimiter, standard minimal quoting and a newline after every row, including the header. Preserve row order, repeats, empty names and zero.
    • No files or network. Do not mutate input or nested rows; each call uses a fresh buffer. Empty input returns header only.
    Guided: export rows faithfullyPYTHON 3

    Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

    Preparing the editor controls. Run and editing become available when this page is interactive.

    Browser Python limits

    Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

    Inspect 6 public checks

    Transparent local learning checks, not exhaustive or tamper-proof grading.

    1. normal
      assert export_minutes([["Ada",2],["Lin",3]]) == "name,minutes\nAda,2\nLin,3\n"
    2. empty
      assert export_minutes([]) == "name,minutes\n"
    3. quoted comma
      assert export_minutes([["Ada, A.",15]]) == 'name,minutes\n"Ada, A.",15\n'
    4. quotes and newline
      assert export_minutes([['A"B\nC',0]]) == 'name,minutes\n"A""B\nC",0\n'
    5. repeats and empty name
      assert export_minutes([["",0],["A",2],["A",2]]) == "name,minutes\n,0\nA,2\nA,2\n"
    6. nested ownership
      rows = [["Lin",3],["Ada",2]]
      first = rows[0]
      assert export_minutes(rows) == "name,minutes\nLin,3\nAda,2\n" and rows == [["Lin",3],["Ada",2]] and rows[0] is first and export_minutes([]) == "name,minutes\n"
      Why specify a line terminator?

      It makes exact output portable for this contract. For b output characters and n rows, writing is O(b + n), with O(b) buffer/result storage. It is not a large-file streaming exporter.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: accept names, not arbitrary paths

      Change from parsing report contents to validating a deliberately narrow filename policy.

      The contract

      • Input is a list of strings. Keep a name only if it is an ASCII stem of one or more letters, digits, _ or -, followed by exactly lowercase .csv. No separators, dots in the stem, spaces or absolute names are allowed.
      • Return a fresh list of accepted names in original order, including duplicates. Empty input gives a fresh empty list; rejected names are omitted, not normalised.
      • Preserve input. Pure in-memory naming policy only: this does not prove filesystem containment, authorisation or file existence.
      Transfer: accept names, not arbitrary pathsPYTHON 3

      Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

      Preparing the editor controls. Run and editing become available when this page is interactive.

      Browser Python limits

      Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

      Inspect 6 public checks

      Transparent local learning checks, not exhaustive or tamper-proof grading.

      1. accepted
        assert report_names(["daily.csv","A_2-x.csv"]) == ["daily.csv","A_2-x.csv"]
      2. empty ownership
        a = report_names([])
        b = report_names([])
        assert a == [] and b == [] and a is not b
      3. duplicates and order
        assert report_names(["z.csv","a.csv","z.csv"]) == ["z.csv","a.csv","z.csv"]
      4. paths rejected
        assert report_names(["../a.csv","/a.csv","dir/a.csv","dir\\a.csv","C:a.csv"]) == []
      5. exact policy
        assert report_names([".csv","a.CSV","a.b.csv"," a.csv","é.csv","a.csv\n"]) == []
      6. input preserved
        names = ["../x.csv","good.csv","good.csv"]
        result = report_names(names)
        assert result == ["good.csv","good.csv"] and result is not names and names == ["../x.csv","good.csv","good.csv"]
        Why not strip directories and accept the basename?

        That silently changes a rejected request and can cause name collisions. For b total name characters, full matching is O(b) for this simple fixed-shape pattern, with O(a) result references for a accepted names. Filesystem policy remains separate.

        A GOOD PLACE TO PAUSE

        Core route complete.

        If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.

        Save your core reading milestone

        Bound memory and errors

        A bounded pipeline limits both the input it accepts and the state it retains. Reading one row at a time alone does not bound every resource.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        A report importer should fail predictably instead of accepting endless rows or enormous fields. Put limits near their source and explain what each one does. This example adds a record-count limit to the earlier running total.

        Words you will see

        Budget
        An explicit maximum permitted amount of a resource.
        Cardinality
        How many distinct values a group or set contains.
        Logical record number
        The sequence position of a parsed row, which can differ from its physical line number.

        Limit the promise you can actually enforce

        enumerate counts data records from one. The comparison rejects the first record beyond limit before adding it. Two records fit exactly. The parser has already produced the over-limit row before the condition runs, so this is not a byte or field-length guard.

        A full boundary needs a byte cap before reading, a field-length policy in the parser, a maximum record count and bounded diagnostics. If you also group by name, a cap on rows does not justify calling the group map constant-sized. Its size grows with the number of distinct names.

        Reject with context instead of fabricating partial success

        For a financial or audited total, propagating an error is often safer than returning a partial sum that looks complete. If partial import is intentional, return accepted and rejected counts with the result, not a silent fallback. Include the logical record number in diagnostics and distinguish it from csv's physical line tracking.

        For n bounded-width rows a running sum takes O(n) conversion steps and retains one row plus the accumulator. Wider integers and cells cost more. The StringIO fixture still occupies memory here; no filesystem, network or unbounded live feed is used.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. limit = 2

          Set an inclusive cap on data records.

        2. total = 0

          Keep only a running sum.

        3. for number, row in enumerate(csv.DictReader(StringIO(text)), 1):

          Number parsed rows, not headers.

        4. if number > limit:

          Reject a third row if one appears.

        5. total += int(row["minutes"])

          Add the two permitted values.

        6. print(total)

          Display 5 only after the complete input passes the cap.

        Streaming avoids holding the entire file, but accumulating all unique groups can still be unbounded. Limit input bytes, field lengths, distinct groups and error samples. Capture row numbers and reject invalid units instead of silently treating malformed values as zero.

        Predict before you run

        Does the second row exceed limit = 2?

        Reject excess recordsPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Make the cap too small.

        Try: Change limit = 2 to limit = 1.

        The second row raises before its minutes are added.

        Observe logical numbering.

        Try: Add print(number) immediately before the if.

        The original prints record numbers 1 and 2, then total 5.

        Before you move on

        Can a two-record cap stop a single record with a billion-character cell before it is parsed?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        No. The row-count check happens after parsing that row. Bound bytes and field sizes earlier as separate controls.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Safe output replacement

        Safe CSV output is fully prepared before it replaces a published result. Correct quoting and safe publication solve different failure modes.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        A quoted name must survive export, and a failed export should not destroy the last good report. csv.writer solves field representation. Preparing a separate candidate lets the application decide when it becomes current.

        Words you will see

        Writer
        An object that encodes fields according to CSV rules.
        Line terminator
        The characters used to end each output record.
        Publication boundary
        The step where a finished candidate becomes visible as the current result.

        Finish encoding before publishing

        The buffer receives a header then one data record. csv.writer quotes Ada, A. because it contains a delimiter. lineterminator='\n' chooses deterministic output for this exercise. getvalue copies out the complete string while the stream is open; it remains usable after the buffer closes.

        current changes only after the with block. If writing raised before candidate was complete, that assignment would not run. Building all output text uses memory proportional to its length; streaming into a separate real file is preferable for outputs too large to buffer.

        Do not confuse a model with a disk guarantee

        This is a browser-local publish model. A supported local application can prepare a separately named file on the same filesystem and replace its destination after success. Direct mode-w writes truncate too early. Atomic replacement depends on the filesystem and does not by itself promise power-loss durability or resolve competing writers.

        CSV quoting also does not neutralise spreadsheet formulas in untrusted cells. A spreadsheet-export policy is a separate requirement that may change the represented data. Keep raw machine-exchange CSV and human spreadsheet safety policies explicit rather than assuming quotes make every downstream use safe.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. current = "old report"

          Keep a previous published value.

        2. with StringIO(newline="") as buffer:

          Own a separate output buffer.

        3. writer = csv.writer(buffer, lineterminator="\n")

          Choose CSV encoding and stable newline characters.

        4. writer.writerow(["name", "minutes"])

          Write the two-column header.

        5. writer.writerow(["Ada, A.", 15])

          Encode the comma-containing name safely.

        6. candidate = buffer.getvalue()

          Extract completed text before closure.

        7. current = candidate

          Publish after preparation.

        8. print(current, end="")

          Display existing terminators without adding another newline.

        Writing directly to the destination with mode w truncates it immediately. For important reports, write a temporary file in the same filesystem and replace atomically after success. Atomic rename does not by itself guarantee power-loss durability; document the required guarantees.

        Predict before you run

        Why is Ada's name surrounded by quotes?

        Prepare a CSV result in memoryPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Try an embedded quote.

        Try: Replace Ada, A. with Ada "A".

        csv.writer quotes the field and doubles its internal quotes.

        Change the CSV dialect deliberately.

        Try: Pass delimiter=";" to csv.writer.

        The header uses semicolons and the name's comma no longer requires quoting by itself.

        Before you move on

        Does quoting a value beginning with = make it safe for every spreadsheet?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        No. CSV quotes describe field boundaries, not spreadsheet execution policy. Decide and document a separate export policy for untrusted spreadsheet cells.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Make the explanation your own.

        Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.

        Take a versioned study copy

        Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.

        Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.

        REFLECT, THEN CONTINUE

        Make this a milestone.

        Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.

        Your account

        Loading account...

        Sign in to save your work across devices.