How to Create a CSV File in Python

Python's standard library ships with a `csv` module — no install required. Use `csv.writer` for simple row lists, `csv.DictWriter` when your data is dictionaries, and pandas' `df.to_csv()` when you're already working with DataFrames.

Generate matching mock data right now

No sign-up, runs 100% in your browser, exports straight to CSV.

csv.writer — basics

import csv

with open('people.csv', 'w', newline='', encoding='utf-8') as f:
    w = csv.writer(f)
    w.writerow(['name', 'email', 'country'])
    w.writerow(['Ada', 'ada@example.com', 'UK'])
    w.writerow(['Grace', 'grace@example.com', 'US'])

The newline='' argument is required on Windows to avoid blank lines between rows.

csv.DictWriter — when data is dicts

import csv

rows = [
    {'name': 'Ada', 'email': 'ada@example.com'},
    {'name': 'Grace', 'email': 'grace@example.com'},
]

with open('people.csv', 'w', newline='', encoding='utf-8') as f:
    w = csv.DictWriter(f, fieldnames=['name', 'email'])
    w.writeheader()
    w.writerows(rows)

pandas — when you have a DataFrame

import pandas as pd

df = pd.DataFrame({'name': ['Ada', 'Grace'], 'email': ['ada@example.com', 'grace@example.com']})
df.to_csv('people.csv', index=False, encoding='utf-8')

index=False prevents pandas from writing the row index as the first column.

Frequently asked questions

Why do I get blank rows in my CSV on Windows?

Add `newline=''` to your `open()` call. Without it, Windows writes `\r\r\n` between rows.

How do I write a semicolon-delimited CSV?

Pass `delimiter=';'` to `csv.writer` or `delimiter=';'` to `df.to_csv`.

Related guides

Start generating free mock CSVs

High-fidelity mock tables for tests, demos, or models. No sign-ups, completely local.