Python
csv.writer
Learn to write CSV with csv.writer.
Writing rows with csv.writer
To write to a CSV file, create a writer object with csv.writer(f). writerow(["name", "age"]) writes a single row; writerows([["Ayşe", 30], ["Ali", 25]]) writes multiple rows in one call.
The writer separates values with commas and quotes them when needed — for instance, if a value contains a comma it writes "Ahmet, Senior" with double quotes. This keeps the file safe to read back. You don't deal with commas and quotes by hand.
Bulk writing with writerows
To write many rows at once you use writerows. The parameter is a list whose items are rows: writer.writerows([header, row1, row2]). This is shorter than calling writerow in a loop.
For large writes writerows also gives a performance boost; it flushes the buffer in one go. Still, watch memory for very large lists; streaming data in chunks is better for those.
Exercise Write two rows with writerows and read back
Start with import csv. In a with open("products.csv", "w", encoding="utf-8", newline="") as f: block write writer = csv.writer(f), then writer.writerows([["name", "price"], ["pen", 5], ["notebook", 10]]) to write three rows (header included). Then in a with open("products.csv", "r", encoding="utf-8", newline="") as f: block do rows = list(csv.reader(f)) and print(len(rows)).
Show example solution
import csv
# Write three rows (header + two data) with writerows
with open("products.csv", "w", encoding="utf-8", newline="") as f:
writer = csv.writer(f)
writer.writerows([["name", "price"], ["pen", 5], ["notebook", 10]])
# Read with csv.reader and print the row count
with open("products.csv", "r", encoding="utf-8", newline="") as f:
rows = list(csv.reader(f))
print(len(rows))
Test yourself
-
Complete the writerow method
writer = csv.writer(f)
writer.____(["name", "age"])
Show answer
writer = csv.writer(f)
writer.writerow(["name", "age"])
-
What does writer.writerows(...) accept?
- A single number
- A single string
- A list of rows
- A dictionary
Show answer
A list of rows — writerows writes many rows in one call.
-
Match the csv.writer concepts
- csv.writer
- Creates a writer object
- writerow
- Writes one row
- writerows
- Writes many rows
- newline=""
- Line-ending setting
Next lesson: DictReader and DictWriter