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
