CodeBlanks Logo Icon CodeBlanks

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.

Practice 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)).

Starter code

main.py
import csv

# Write three rows (header + two data) with writerows
# Read with csv.reader and print the row count

Sample solution

main.py
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))

Expected output

3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the writerow method

Question
writer = csv.writer(f)
writer.____(["name", "age"])
Answer
writer = csv.writer(f)
writer.writerow(["name", "age"])

Explanation: writerow writes a single row.

2 What does writer.writerows(...) accept?

  • A single number
  • A single string
  • A list of rows Correct answer
  • A dictionary

Explanation: writerows writes many rows in one call.

3 Match the csv.writer concepts

Term Meaning
csv.writer Creates a writer object
writerow Writes one row
writerows Writes many rows
newline="" Line-ending setting

All lessons in Intermediate