Writing CSV

Use csv.writer and csv.DictWriter to create CSV files

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

Writing with csv.writer

csv.writer writes rows from lists. Call writerow() for one row or writerows() for multiple rows.

import csv

with open("output.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["name", "score"])   # header
    writer.writerow(["Alice", 95])

Always pass newline="" when opening a CSV file for writing. Without it, Python adds extra blank lines on Windows.

Writing with csv.DictWriter

csv.DictWriter writes rows from dictionaries. You specify the column names with fieldnames, then call writeheader() to write the header row.

headers = ["name", "score"]

with open("output.csv", "w", newline="") as file:
    writer = csv.DictWriter(file, fieldnames=headers)
    writer.writeheader()
    writer.writerows([{"name": "Alice", "score": 95}])

Instructions

Write the same data to two CSV files — one using csv.writer, one using csv.DictWriter.

  1. Import csv.
  2. Open scores.csv in write mode with newline="". Create a csv.writer named writer. Call writer.writerow(["name", "score"]). Call writer.writerow(["Alice", 95]). Call writer.writerow(["Bob", 82]).
  3. Call print("scores.csv written with csv.writer.").
  4. Create headers = ["name", "score"] and rows = [{"name": "Alice", "score": 95}, {"name": "Bob", "score": 82}].
  5. Open scores_dict.csv in write mode with newline="". Create a csv.DictWriter named writer with fieldnames=headers. Call writer.writeheader(). Call writer.writerows(rows).
  6. Call print("scores_dict.csv written with csv.DictWriter.").