smartyfy.mrindigi.com

Python Master Course V2 — 075. CSV Files

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 07 · LESSON 075 OF 200

CSV Files

Study time: 75–100 minutes · Prerequisites: functions, exceptions, pathlib and Lesson 74.

Course hub

Video lesson

Video not yet available. Reserved for a verified lesson video URL/player.

Learning outcomes

Read structured tabular text with DictReader. You will also identify failure cases, predict outputs, apply the concept in a small application, and test the result.

Understand CSV Files

CSV describes fields, not Python types

CSV is a text format for rows of fields. A delimiter, usually a comma, separates fields, while quoting lets a field contain that delimiter or even a newline. Splitting each line on a comma is not a CSV parser: the name “Asha, Rao” is one quoted field, not two columns. Python’s csv module understands these quoting rules and can handle different delimiter conventions when the format is specified.

DictReader uses the header row to associate column names with field text. By default, values remain strings: a score of 90 arrives as "90", not the integer 90. Parsing the CSV structure and validating the meaning of its fields are separate jobs. Define required headers, accepted blanks, number formats and range limits before calculating results. This lesson requires exactly the ordered headers name and score, a nonempty name and an integer score from 0 through 100.

Python
import csv
from io import StringIO

def read_marks(source):
    reader = csv.DictReader(source, strict=True)
    if reader.fieldnames != ["name", "score"]:
        raise ValueError("headers must be exactly name,score")
    accepted, rejected = [], []
    for row in reader:
        line_number = reader.line_num
        if None in row or any(value is None for value in row.values()):
            rejected.append((line_number, "wrong field count"))
            continue
        name = row["name"].strip()
        if not name:
            rejected.append((line_number, "name is required"))
            continue
        try:
            score = int(row["score"])
        except ValueError:
            rejected.append((line_number, "score must be an integer"))
            continue
        if not 0 <= score <= 100:
            rejected.append((line_number, "score must be between 0 and 100"))
            continue
        accepted.append({"name": name, "score": score})
    return accepted, rejected

text = """name,score
"Asha, Rao",90
Ravi,80
Mira,wrong
,70
"""
accepted, rejected = read_marks(StringIO(text, newline=""))
print(accepted)
print(rejected)
Expected output
[{'name': 'Asha, Rao', 'score': 90}, {'name': 'Ravi', 'score': 80}]
[(4, 'score must be an integer'), (5, 'name is required')]

Separate structural and row-level errors

The header check runs before any row is accepted. It catches absent, reordered, extra or duplicate headers under this intentionally strict schema. DictReader stores extra unnamed fields under the None key and fills missing fields with None, so the field-count check rejects both shapes. A blank field is an empty string and needs its own rule. The integer conversion rejects text such as 90.5 rather than rounding it into a passing score.

The error location uses reader.line_num, which counts physical source lines consumed. A quoted field may span several physical lines, so this is the ending physical line of the record, not always its sequential row number. Malformed quoting can raise csv.Error even with per-row validation; catch that at the import boundary and mark the file structurally invalid rather than claiming every later row was processed. File and decoding errors also belong at that boundary.

Write CSV with a writer, not manual commas

Run after the previous example
destination = StringIO(newline="")
writer = csv.DictWriter(destination, fieldnames=["name", "score"],
                        lineterminator="\n")
writer.writeheader()
writer.writerows(accepted)
print(destination.getvalue(), end="")
Expected output
name,score
"Asha, Rao",90
Ravi,80

DictWriter quotes the comma-containing name correctly and writes columns in the declared order. For real files, use path.open("r", encoding="utf-8", newline="") for reading and an explicitly chosen write mode with the same encoding/newline settings for writing. Let the csv module manage record newlines; platform text translation can otherwise interfere. Choose a separate output path and avoid overwriting the source while an import is still being validated.

The reference function returns accepted and rejected lists so the beginner can inspect every result. For very large files, stream accepted records to a controlled destination and bound the error report rather than retaining everything. Test quoted commas, an empty file, header-only input, missing and extra fields, score 0, score 100 and an out-of-range value. If output will be opened in spreadsheet software, establish an additional policy for formula-like text; CSV quoting alone does not stop spreadsheet formula interpretation. See the csv documentation.

Progressive runnable Python example

Requires Python 3.10+. Run in a disposable practice folder. Save as lesson75.py and execute with python lesson75.py or python3.

import csv
from io import StringIO
rows=list(csv.DictReader(StringIO('name,score\nAsha,90\nRavi,80\n')))
print(len(rows))
print(rows[0]['name'])

Expected output:

2
Asha

How to reason through the example

Identify which operation opens, parses, writes or transforms data. Trace each value from source to output. Note whether any file is created and whether repeated execution changes the result. Next, alter one value, predict the result, run the example and compare your prediction.

Additional code exercise — Schema and boundary checks

Run these checks in the same script after defining read_marks and importing StringIO above.

assert read_marks(StringIO("name,score\n")) == ([], [])
accepted, rejected = read_marks(StringIO("name,score\nLow,0\nHigh,100\nOver,101\n"))
assert [row["score"] for row in accepted] == [0, 100]
assert rejected == [(4, "score must be between 0 and 100")]
for invalid_header in ("", "score,name\n", "name,name\n"):
    try:
        read_marks(StringIO(invalid_header))
    except ValueError:
        pass
    else:
        raise AssertionError("invalid header was accepted")
print("CSV boundary checks passed")

Expected: CSV boundary checks passed. Add missing-field, extra-field and malformed-quote tests as your next practice task.

Guided practical project

Project brief: Build a marks import validator with rejected-row reasons and a summary report.

  1. Specify input format, accepted fields and error policy.
  2. Create a small sample dataset with three valid and two invalid records.
  3. Write a parser and validator that report errors with record numbers.
  4. Implement the transformation as a separate testable function.
  5. Write results to a different destination rather than overwriting source files.
  6. Test empty, malformed, boundary and ordinary cases.
  7. Document setup, expected output and recovery procedure.

Mastery requirements: at least three automated tests, explicit error handling and a reproducible example. This is an assignment, not a claim that the complete project has been executed on the website.

Common mistakes and debugging

  • Assuming the process working directory is the same as the script directory.
  • Relying on platform-dependent encodings.
  • Trusting records without checking required fields or types.
  • Overwriting input files before verifying transformed output.
  • Catching every exception and hiding the underlying failure.

Debug systematically: reproduce a failure with the smallest record, inspect the exception and offending input, correct the cause, and add a regression test.

Practice and explained answers

Try each question before opening its answer. Predict code results on paper, then compare them with the explanation.

Optional hint for question 1

The comma is inside quotes; ask whether it separates columns or belongs to the name.

1. Why is splitting on commas wrong for the name Asha, Rao?

Answer and reasoning:

The quoted field contains a comma that is data. A CSV parser recognizes the quote boundaries, while a plain split creates an extra column and corrupts the record shape.

2. What type is score immediately after DictReader reads it?

Answer and reasoning:

A string under this reader configuration. Convert it explicitly and validate its range before arithmetic. A valid CSV row can still contain invalid application data.

3. How are missing and extra fields represented by DictReader?

Answer and reasoning:

With the defaults, missing fields receive None values, and extra fields are placed in a list under the None key. Check both conditions instead of assuming the header guarantees every row has the same width.

4. Why use newline="" when opening CSV files?

Answer and reasoning:

It leaves newline handling to the csv module, which understands record terminators and quoted embedded newlines. Explicit UTF-8 separately controls text decoding and encoding.

5. What should a header-only file and an empty file do under this contract?

Answer and reasoning:

The header-only file with exactly name,score returns two empty lists because its schema is valid but there are no records. An entirely empty file has no headers and raises ValueError. Those are deliberately different outcomes.

6. What needed repair in the original CSV fixture?

Answer and reasoning:

The source needs real line separators, represented by intact backslash-n escapes or a clearly shown multiline string. The earlier literal name,scorenAsha,90nRavi,80n was one header line, so it could not produce two data rows and indexing rows[0] failed. The warmup example now preserves those escapes.

Knowledge check

Use the topic-specific practice questions above to check your understanding. Attempt each answer before opening its explanation.

Return to the practice questions ↑

Mastery checkpoint

Demonstrate the sample, explain its output, implement the project, test three edge cases, and describe your error-handling policy. The video remains unavailable and learner completion is not account-synchronized.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.