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
- Prepare a list of dictionaries.
- Open the output with
"w",newline="", utf-8. - Create
DictWriter(f, fieldnames=[...]). - Call
writeheader()thenwriterows(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.
Ravindra Bagale's Tip – मराठी
Windows वर CSV लिहिताना newline="" वापरा. नाहीतर rows मध्ये रिकाम्या lines येतात.
Ravindra Bagale's Tip – हिंदी
Windows पर CSV लिखते समय newline="" इस्तेमाल करो. वरना rows के बीच खाली lines आती हैं.