Reading a CSV file into an array of records

Tip: Choose Save as PDF in the print dialog to download. Use A4 paper size.

Reading a CSV file into an array of records

Name:
Date:
Class:

Quick Questions

Shade in the A or B circle for each question.

1. Which line turns one CSV line into a record of fields and adds it to a list?
A records.split(line.strip().append(','))
B records.append(line.strip().split(','))
2. After reading a CSV file with 5 data rows into records, what does records[0] hold?
A The fields of the first row, as a list
B The whole file as one long string
3. A CSV file has a header row: name,mark. How do you skip it while reading?
A Call next(file) once before the loop
B Call records.pop() before the loop
4. Why does the line.strip() part matter in line.strip().split(',')?
A It removes every comma from the line
B It removes the trailing newline so the last field is clean
5. Fields read from a CSV file are always strings. Which converts the mark field to a number?
A int(fields[1])
B fields[1].int()

Match the Pairs

Draw a line connecting each item on the left to its match on the right.

Left columnRight column
1next(reader) ARemoves the newline, splits the line at each comma and adds the fields to the list as one record
2records.append(line.strip().split(',')) BThe whole line is appended as one long string. It is never split into fields, so the list is not a table of records.
3Each field is read from a file as a string, so a numeric field must be converted before it is used in calculations CSkips the header row by reading and discarding the first line before the loop reads the data rows
4The csv module reader splits every line into a list of fields for you, so you can loop over the rows directly Drecord[2] = int(record[2])
5records = [] for line in file: records.append(line) EThe header row is not skipped, so the column names are stored as a record and mixed in with the real data.
6for line in file: records.append(line.strip().split(',')) # header row is included Ffor row in csv.reader(file):

Definitions

records.append(line.strip().split(','))

Fill in the Blanks

Complete each line of code by filling in the missing parts.

1.
for line in file: records.append(line.strip()._____(','))
2.
file = open('students.csv') ____(file) for line in file:
3.
parts = line.strip().split(',') records.append([parts[0], ___(parts[1])])
4.
import csv reader = csv.______(file) records = list(reader)
5.
records = [] for line in file: records.append(line._____().split(','))

Spot the Error

Shade in the letter of the line that contains an error.

Question 1
A rows = []
B f = open('data.csv')
C for ln in f:
D p = ln.strip().split(' ')
E rows.append(p)
Question 2
A records = []
B with open('marks.csv') as f
C for line in f:
D p = line.split(',')
E records.append(p)
Question 3
A f = open('s.csv')
B f.next()
C rows = []
D for ln in f:
E rows.append(ln.split(','))
Question 4
A records = []
B for ln in open('s.csv'):
C p = ln.strip().split(',')
D int(p[1])
E records.append(p)
Question 5
A import csv
B with open('s.csv') as f:
C reader = csv.read(f)
D rows = list(reader)

Answer Key

Reading a CSV file into an array of records
Section A: Quick Questions
Q1
B — records.append(line.strip().split(','))
Q2
A — The fields of the first row, as a list
Q3
A — Call next(file) once before the loop
Q4
B — It removes the trailing newline so the last field is clean
Q5
A — int(fields[1])
Section B: Match the Pairs
Q1
next(reader) → Skips the header row by reading and discarding the first line before the loop reads the data rows
Q2
records.append(line.strip().split(',')) → Removes the newline, splits the line at each comma and adds the fields to the list as one record
Q3
Each field is read from a file as a string, so a numeric field must be converted before it is used in calculations → record[2] = int(record[2])
Q4
The csv module reader splits every line into a list of fields for you, so you can loop over the rows directly → for row in csv.reader(file):
Q5
records = [] for line in file: records.append(line) → The whole line is appended as one long string. It is never split into fields, so the list is not a table of records.
Q6
for line in file: records.append(line.strip().split(',')) # header row is included → The header row is not skipped, so the column names are stored as a record and mixed in with the real data.
Section C: Definitions
Q1
records.append(line.strip().split(',')) — Splits one CSV line into fields and appends them as one record to a list, so each row of the file becomes a record and the whole file becomes a table in memory.
Section D: Fill in the Blanks
Q1
for line in file: records.append(line.strip().split(','))
Q2
file = open('students.csv') next(file) for line in file:
Q3
parts = line.strip().split(',') records.append([parts[0], int(parts[1])])
Q4
import csv reader = csv.reader(file) records = list(reader)
Q5
records = [] for line in file: records.append(line.strip().split(','))
Section E: Spot the Error
Q1
D — A CSV file separates fields with commas, so the line must be split on ','. Splitting on a space leaves each row as one big field. It should be split(',').
Q2
B — A with statement must end with a colon. Without it Python raises a SyntaxError. It should be: with open('marks.csv') as f:
Q3
B — File objects have no .next() method in Python 3, so this raises an AttributeError. Use the built-in next(f) to skip the header row.
Q4
D — int(p[1]) creates a number but the result is thrown away, so the field stays a string. Assign it back: p[1] = int(p[1]).
Q5
C — The csv module has no read() function. The function that reads rows as lists of fields is csv.reader(f).