Writing records to a CSV file

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

Writing records to a CSV file

Name:
Date:
Class:

Quick Questions

Shade in the A or B circle for each question.

1. Which line joins the fields of a record list called record into one CSV line?
A line = ','.join(record)
B line = record.join(',')
2. record = ['Ava', 16, 'Red']. What happens when you run ','.join(record)?
A 'Ava,16,Red'
B TypeError, because 16 is not a string
3. Which record is safe to pass to ','.join()?
A ['Ava', str(16), 'Red']
B ['Ava', 16, 'Red']
4. You write a line to a CSV file with file.write(line). What is missing so each record sits on its own row?
A file.write(line + '\n')
B file.write(line + ',')
5. Which approach writes a header row to a new CSV file correctly?
A file.write(['name', 'age'])
B file.write(','.join(['name', 'age']) + '\n')

Match the Pairs

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

Left columnRight column
1','.join(record) Afile.write('name,mark\n')
2str(record[2]) BJoins the string fields of a record into one comma-separated line ready to write to a CSV file
3Write a header row first so the CSV file has column names, then the data lines CNo newline is added, so every record ends up on the same line. Add + '\n' after the joined text.
4Append a new record to the end of an existing CSV file without erasing the old lines DConverts a number field to a string so it can be joined into a CSV line
5line = ','.join(['Ava', 88]) Eopen('marks.csv', 'a')
6file.write(','.join(record)) FThe number 88 is not a string, so join() causes a TypeError. Use str(88) first.

Definitions

','.join(record)

Fill in the Blanks

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

1.
line = ','.____(record)
2.
line = ','.join([name, ___(score)])
3.
row = [name, str(score)] f._____(','.join(row) + '\n')
4.
with open('scores.csv', '_') as f: f.write(','.join(row) + '\n')
5.
header = ','.join(['Name', 'Score']) f.write(______ + '\n')

Spot the Error

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

Question 1
A f = open("pupils.csv", "r")
B row = ["Ava", "16", "Red"]
C line = ",".join(row)
D f.write(line + "\n")
E f.close()
Question 2
A row = ["Liam", 15, "Blue"]
B line = ",".join(row)
C with open("p.csv", "a") as f:
D f.write(line + "\n")
Question 3
A with open("s.csv", "w") as f:
B f.write("item price\n")
C row = ["Pen", str(1.5)]
D line = ",".join(row)
E f.write(line + "\n")
Question 4
A row = ["Zoe", str(88), "A"]
B line = row.join(",")
C f = open("marks.csv", "a")
D f.write(line + "\n")
E f.close()
Question 5
A f = open("kids.csv", "w")
B r = ["Al", "7"]
C f.write(",".join(r) + "/n")
D f.close()

Answer Key

Writing records to a CSV file
Section A: Quick Questions
Q1
A — line = ','.join(record)
Q2
B — TypeError, because 16 is not a string
Q3
A — ['Ava', str(16), 'Red']
Q4
A — file.write(line + '\n')
Q5
B — file.write(','.join(['name', 'age']) + '\n')
Section B: Match the Pairs
Q1
','.join(record) → Joins the string fields of a record into one comma-separated line ready to write to a CSV file
Q2
str(record[2]) → Converts a number field to a string so it can be joined into a CSV line
Q3
Write a header row first so the CSV file has column names, then the data lines → file.write('name,mark\n')
Q4
Append a new record to the end of an existing CSV file without erasing the old lines → open('marks.csv', 'a')
Q5
line = ','.join(['Ava', 88]) → The number 88 is not a string, so join() causes a TypeError. Use str(88) first.
Q6
file.write(','.join(record)) → No newline is added, so every record ends up on the same line. Add + '\n' after the joined text.
Section C: Definitions
Q1
','.join(record) — Joins a record's fields, which must all be strings, into one comma-separated line. Use str() on numbers first, then write the line plus a newline to the CSV file.
Section D: Fill in the Blanks
Q1
line = ','.join(record)
Q2
line = ','.join([name, str(score)])
Q3
row = [name, str(score)] f.write(','.join(row) + '\n')
Q4
with open('scores.csv', 'a') as f: f.write(','.join(row) + '\n')
Q5
header = ','.join(['Name', 'Score']) f.write(header + '\n')
Section E: Spot the Error
Q1
A — Mode "r" opens the file for reading only, so f.write() would fail. To save records the file must be opened in write mode: open("pupils.csv", "w").
Q2
A — 15 is an integer, and join() only accepts strings, so line 2 would crash with a TypeError. Convert the number first with str(15).
Q3
B — The header row must use commas to separate the column names, like the data rows. It should be f.write("item,price\n").
Q4
B — join() is a string method, and lists have no join method. The separator string comes first and the record goes inside the brackets: ",".join(row).
Q5
C — The newline character is \n with a backslash. "/n" would write the literal characters /n into the file instead of ending the line. It should be "\n".