Ravindra BagaleCourses & study guides मराठी Track your progress

How to Read and Write CSV, JSON and Text Files in Python (with open and with)

P9.4 How to Write a CSV File in Python

Why. You will save cleaned or summary data for Excel, Power BI or a teammate.

What. csv.DictWriter writes dictionaries as rows. You give it the column names (fieldnames).

How.

Write a CSV

  1. Prepare a list of dictionaries.
  2. Open the output with "w", newline="", utf-8.
  3. Create DictWriter(f, fieldnames=[...]).
  4. Call writeheader() then writerows(rows).

Worked example A — Save a summary.

Step 1 — What we do. A hospital in Leeds saves patients per ward.

Step 2 — Type and run this code.

import csv
rows = [{"ward": "A", "patients": 24}, {"ward": "B", "patients": 31}]
with open("wards.csv", "w", newline="", encoding="utf-8") as f:
    w = csv.DictWriter(f, fieldnames=["ward", "patients"])
    w.writeheader()
    w.writerows(rows)
print(open("wards.csv", encoding="utf-8").read())

Step 3 — Output you should see.

ward,patients
A,24
B,31

Step 4 — What it means. The file has a header line and one line per ward. Excel opens it directly.

Ravindra Bagale's Tip

Use newline="" when writing CSVs on Windows. Without it you get empty lines between rows.