liveBook · Manning

Csv.reader

As explained in Python How-To

csv.reader is a Python standard-library factory that creates an iterator for parsing delimited text rows into sequences of fields.

Need to display records stored in a CSV file? Call csv.reader with an open file object. It returns an iterator whose items are lists of comma-separated field values, ready for a for loop. section 11.2.1

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']

Read tasks.txt with newline="", create a reader, and print each row as a list of strings. section 11.2.1

Choose the form that fits the job:

  • Iterate directly when processing one row at a time. section 11.2.1
  • Wrap the reader with list() when the complete set of rows is needed in memory. section 11.2.1
  • Unpack each row and convert selected string fields when constructing application objects. section 14.2.3

Loading task records

A task application can open its CSV data source, iterate through csv.reader, unpack each row, convert urgency and status values, and filter rows before returning Task objects. section 14.2.3

with open("tasks.txt", newline="") as file:
   csv_reader = csv.reader(file)
   tasks_rows = list(csv_reader)
   print(tasks_rows)

# output the following line:
[['1001', 'Homework', '5'], ['1002', 'Laundry', '3'], 
 ['1003', 'Grocery', '4']]

Materialize every parsed row with tasks_rows = list(csv_reader) when later operations need the complete collection. section 11.2.1

How Python How-To covers it

How deep it goes
Explains reader creation, iterator behavior, row lists, list materialization, unpacking, and application-level conversions.
Examples
Uses tasks.txt rows and a Taskier task database with six-field records, filtering, and object construction.
What it assumes
Uses file opening and for-loop iteration while teaching reader creation and row-level processing.
What you can do after
Apply it via Python's csv module to iterate over CSV rows or materialize them as a list.
How it connects
Connects CSV files with the csv module, file objects, iterators, for loops, tuple unpacking, filtering, and type conversion.

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.