Pylerno
English

CSV

Read records by column name and convert text fields deliberately.

On this page

The concept

CSV represents tabular rows with delimiters and quoting rules. DictReader maps header names to field values, and DictWriter uses declared fieldnames to write consistent columns. Most values read by DictReader are strings, even when the source cells contain digits.

Use newline="" when opening CSV files so the csv library manages line endings. Do not replace CSV parsing with split(","): quoted fields can contain commas and newlines. Validate headers, missing values, and numeric fields according to your application's contract.

Worked example

python
import csv
from pathlib import Path
from tempfile import TemporaryDirectory

rows = [{"name": "Sara", "score": 90}, {"name": "Dana", "score": 75}]
with TemporaryDirectory(prefix="python_csv_") as temporary:
    path = Path(temporary) / "scores.csv"
    with path.open("w", newline="", encoding="utf-8") as file:
        writer = csv.DictWriter(file, fieldnames=["name", "score"])
        writer.writeheader()
        writer.writerows(rows)
    with path.open(newline="", encoding="utf-8") as file:
        for row in csv.DictReader(file):
            print(row["name"], int(row["score"]) + 5)

Trace the result

  1. The writer declares name and score and writes the header once.
  2. writerows serializes each record using those column names.
  3. The reader converts score to int before adding five; concatenating the raw text would mean something else.
text
Sara 95
Dana 80
Line-by-line walkthrough

Line 1: import csv

Load csv (CSV quoting, headers, and row processing). Importing makes these names available; it is not a call to every function in the module.

Line 2: from pathlib import Path

Import Path from pathlib. This supplies filesystem path values. The caller can now use the imported names directly.

Line 3: from tempfile import TemporaryDirectory

Import TemporaryDirectory from tempfile. This supplies temporary files and directories. The caller can now use the imported names directly.

Line 5: rows = [{"name": "Sara", "score": 90}, {"name": "Dana", "score": 75}]

Evaluate [{'name': 'Sara', 'score': 90}, {'name': 'Dana', 'score': 75}], then bind or update rows with the result. The chosen collection determines how later access, membership, and mutation behave. Assignment itself does not imply a deep copy.

Lines 6–14: with TemporaryDirectory(prefix="python_csv_") as temporary:

Enter the listed context manager(s), run the indented block, and leave each context afterward. The manager defines the cleanup/commit behavior; a database transaction and a file lifetime are not identical contracts.

Line 7: path = Path(temporary) / "scores.csv"

Evaluate Path(temporary) / 'scores.csv', then bind or update path with the result. Assignment itself does not imply a deep copy.

Lines 8–11: with path.open("w", newline="", encoding="utf-8") as file:

Enter the listed context manager(s), run the indented block, and leave each context afterward. The manager defines the cleanup/commit behavior; a database transaction and a file lifetime are not identical contracts.

Line 9: writer = csv.DictWriter(file, fieldnames=["name", "score"])

Evaluate csv.DictWriter(file, fieldnames=['name', 'score']), then bind or update writer with the result. The call finishes before its return value is bound; a failed call does not produce a successful assignment. Assignment itself does not imply a deep copy.

Line 10: writer.writeheader()

Call writer.writeheader to write the declared CSV column names. This call may have an effect even when its return value is not assigned.

Line 11: writer.writerows(rows)

Call writer.writerows to serialize the supplied CSV records. This call may have an effect even when its return value is not assigned.

Lines 12–14: with path.open(newline="", encoding="utf-8") as file:

Enter the listed context manager(s), run the indented block, and leave each context afterward. The manager defines the cleanup/commit behavior; a database transaction and a file lifetime are not identical contracts.

Lines 13–14: for row in csv.DictReader(file):

Obtain each item from csv.DictReader(file) and bind it to row before executing the body. A tuple-shaped target unpacks that item. A loop else, if present, runs only when completion does not use break.

Line 14: print(row["name"], int(row["score"]) + 5)

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Common mistake

A successful row parse does not guarantee required columns or valid numbers. Include row numbers in errors for real imports.

Check your understanding

What does this program print?

python
import csv
print(len(next(csv.reader(['"tea,milk",3']))))
Choose one answer

Search documentation

Share this page