liveBook · Manning

CSV

As explained in Python How-To

A CSV file is a text file that represents tabular data with records and fields separated according to comma-separated-value conventions.

CSV (comma-separated values) is a text format for exchanging tabulated data: rows contain records, and commas separate fields. It suits sales data, exam results, research data, and application storage. section 11.2

Process CSV data in Python with the standard-library csv module:

  • Use csv.reader to iterate over rows, receiving each row as a list of string values. section 11.2.1
  • Open files with newline="" for cross-platform newline handling. section 11.2.1
  • Use csv.DictReader when the first row names the fields; it yields dictionaries keyed by those headers. section 11.2.2
  • Convert the reader to list when the application needs all rows available at once. section 11.2.1

Reading task records

For a tasks.txt file containing task_id,title,urgency followed by task rows, csv.DictReader produces dictionaries such as {'task_id': '1001', 'title': 'Homework', 'urgency': '5'}. The values remain strings in this treatment. section 11.2.2

Listing 11.9 Reading a CSV file using the csv module
import csv                       #1
 
with open("tasks.txt", newline="") as file:
    csv_reader = csv.reader(file)
    for row in csv_reader:
        print(row)
 
# output the following lines:    #2
['1001', 'Homework', '5']
['1002', 'Laundry', '3']
['1003', 'Grocery', '4']

Inspect the complete reader pattern and its printed row output. section 11.2.1

How Python How-To covers it

How deep it goes
Explains row iteration, header mapping, newline handling, and collection, but stops short of writing CSV files.
Examples
Demonstrates tasks.txt containing task IDs, titles, urgency levels, and optional headers.
What it assumes
Assumes basic file handling, iteration, lists, dictionaries, next, zip, and tabular rows.
What you can do after
Apply the csv module to read CSV rows as lists or header-based dictionaries in a Python application.
How it connects
Connects CSV with tabulated data, the csv module, iterators, dictionaries, and SQLite.

Also explained in

Compare how 15 books explain CSV →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.