Lesson 09
CSV Files — csv.writer and csv.reader
Store tabular data rows in a Python CSV file using csv.writer, then read each comma-separated record back using csv.reader.
CSV means comma-separated values. Each line is one record. Each field on that line is separated by a comma. Python's csv module reads and writes those tables.
Use the playground at the bottom of this page, then take the quiz.
What you will learn
- What a CSV file looks like
csv.writer,writerow(), andwriterows()csv.readerfor walking records- Why the open call uses
newline=""
The idea
A CSV file is plain text shaped like a table. Spreadsheet tools can open it. You do not need a spreadsheet library to create it.
csv.writer writes rows. Build it with csv.writer(handle).
| Method | Writes |
|---|---|
writerow(row) |
One row. The row is a list or tuple of fields. |
writerows(rows) |
Many rows. Pass a list of rows. |
Write the header first, then the data rows. writerows accepts a list, tuple, or similar sequence of rows.
csv.reader(handle) yields each record as a list of strings. The header comes out as the first list if you wrote one. Numbers you stored come back as text. Convert them with int() or float() when you need real numbers. That conversion is the same idea as type casting.
Open CSV files in text mode. Pass newline="" so the csv module owns the line endings. Without it, some platforms insert a blank line between rows.
The table in this lesson is a workshop roster with general names. It is not a copy of a sample spreadsheet.
Example
import csv
header = ["code", "label", "topic"]
rows = [
["W-14", "Avery Lane", "Files"],
["W-15", "Jordan Hale", "Streams"],
]
with open("roster.csv", "w", newline="", encoding="utf-8") as handle:
writer = csv.writer(handle)
writer.writerow(header)
writer.writerows(rows)
with open("roster.csv", "r", newline="", encoding="utf-8") as handle:
for row in csv.reader(handle):
print(row)The playground prints four lists: the header and the two people. Every field is a string. Edit a topic and run again.
Key takeaways
-
CSV stores one record per line and commas between fields
-
writerowwrites one row;writerowswrites many -
csv.readeryields each row as a list of strings -
Open with
newline=""in text mode -
Cast numeric fields after reading if you need numbers
-
Previous: Pickling and Unpickling
Loading playground…
Check your understanding
CSV reader and writer quiz
CSV stands for:
1 / 10