Python can write CSV files with the built-in csv module. Use csv.writer() for list-based rows and csv.DictWriter() for dictionary-based rows. Use pandas only when your data is already in a DataFrame. The same open() patterns—modes, encoding, and with blocks—apply as in write to file in Python.
Tested on: Python 3.13.3; kernel 6.14.0-37-generic.
Quick answer: write a CSV file in Python
Open the file with newline="", create a writer, then call writerow() or writerows().
import csv
from pathlib import Path
path = Path("people.csv")
with path.open("w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age"])
writer.writerow(["Alice", 30])This creates people.csv with a header row and one data row. Always use newline="" when writing CSV files.
Python write CSV quick reference
| Task | Use |
|---|---|
| Write one CSV row | writer.writerow(row) |
| Write multiple rows | writer.writerows(rows) |
| Write header row | writer.writerow(["Name", "Age"]) |
| Write dictionaries | csv.DictWriter() |
| Write dictionary header | writer.writeheader() |
| Append CSV row | open(file, "a", newline="") |
| Overwrite CSV file | open(file, "w", newline="") |
| Custom delimiter | csv.writer(file, delimiter=";") |
| Quote fields | quoting=csv.QUOTE_MINIMAL or csv.QUOTE_ALL |
| Avoid blank lines on Windows | newline="" |
| Write DataFrame to CSV | df.to_csv("file.csv", index=False) |
What is a CSV file?
CSV means comma-separated values. It stores rows and columns as plain text and is commonly used for exports, reports, spreadsheets, logs, and data exchange.
Each line is usually one record. Fields in a row are separated by a delimiter, most often a comma.
Write CSV file using csv.writer()
Import csv, open the file in write mode with newline="", create a writer, then write rows.
import csv
import tempfile
from pathlib import Path
path = Path(tempfile.mkdtemp()) / "users.csv"
with path.open("w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age"])
writer.writerow(["Alice", 30])
print(path.read_text(encoding="utf-8"))The csv.writer documentation describes a writer object that converts rows into delimited strings and writes them to a file-like object.
Write header row to CSV
The first row is often the header.
import csv
import tempfile
from pathlib import Path
path = Path(tempfile.mkdtemp()) / "report.csv"
with path.open("w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(["Product", "Price"])
writer.writerow(["Keyboard", 49.99])
writer.writerow(["Mouse", 19.99])
print(path.read_text(encoding="utf-8"))Write the header once, then write data rows below it.
Write multiple rows using writerows()
Use writerows() when you already have a list of rows.
import csv
import tempfile
from pathlib import Path
path = Path(tempfile.mkdtemp()) / "batch.csv"
rows = [
["Name", "City"],
["Alice", "Delhi"],
["Bob", "Mumbai"],
]
with path.open("w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerows(rows)
print(path.read_text(encoding="utf-8"))Each inner list or tuple becomes one CSV row. Do not pass a flat list to writerows().
Append row to existing CSV file
Use mode "a" to append. Use "w" when you want to overwrite the file. Before appending to a path from configuration, confirm the file is present with check if a file exists when your workflow depends on an existing header row.
import csv
import tempfile
from pathlib import Path
path = Path(tempfile.mkdtemp()) / "log.csv"
with path.open("w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(["Event", "Count"])
writer.writerow(["login", 1])
with path.open("a", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(["logout", 1])
print(path.read_text(encoding="utf-8"))Do not write the header again on append unless the file is new.
writerow() vs writerows()
| Method | Use |
|---|---|
writerow(row) |
Write one row |
writerows(rows) |
Write multiple rows |
writeheader() |
Write header when using DictWriter |
Use writerow() inside a loop when rows are generated one at a time. Use writerows() when all rows are already in memory.
Write CSV using DictWriter
Use DictWriter when each row is a dictionary.
import csv
import tempfile
from pathlib import Path
path = Path(tempfile.mkdtemp()) / "people.csv"
rows = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
]
with path.open("w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=["name", "age"])
writer.writeheader()
writer.writerows(rows)
print(path.read_text(encoding="utf-8"))fieldnames controls column order. The DictWriter documentation maps dictionaries onto output rows.
Write CSV with custom delimiter
The default delimiter is a comma. Change it when you need semicolon or pipe separated output.
import csv
import tempfile
from pathlib import Path
path = Path(tempfile.mkdtemp()) / "europe.csv"
with path.open("w", newline="", encoding="utf-8") as file:
writer = csv.writer(file, delimiter=";")
writer.writerow(["name", "score"])
writer.writerow(["Alice", 90])
print(path.read_text(encoding="utf-8"))Write CSV with quotes and special characters
Do not manually join values with commas. Let csv.writer handle quoting when fields contain commas, quotes, or newlines.
import csv
import tempfile
from pathlib import Path
path = Path(tempfile.mkdtemp()) / "notes.csv"
with path.open("w", newline="", encoding="utf-8") as file:
writer = csv.writer(file, quoting=csv.QUOTE_MINIMAL)
writer.writerow(["title", "text"])
writer.writerow(["greeting", 'hello, world'])
writer.writerow(["quote", 'say "hi"'])
print(path.read_text(encoding="utf-8"))Use quoting=csv.QUOTE_ALL when every field should be quoted.
Write CSV with encoding
Use UTF-8 for most modern files.
import csv
from pathlib import Path
path = Path("unicode.csv")
with path.open("w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(["name", "city"])
writer.writerow(["Élodie", "Montréal"])Use encoding="utf-8-sig" when Excel on Windows needs UTF-8 with a BOM.
Avoid extra blank lines in CSV output
Open CSV files with newline="".
import csv
import tempfile
from pathlib import Path
path = Path(tempfile.mkdtemp()) / "safe.csv"
with path.open("w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(["a", "b"])
writer.writerow(["1", "2"])
print(repr(path.read_text(encoding="utf-8")))The Python csv module documentation requires newline="" for CSV file objects. Without it, extra blank rows are a common problem on Windows.
Overwrite vs append CSV file
| Mode | Meaning |
|---|---|
"w" |
Create or overwrite file |
"a" |
Append to existing file |
"x" |
Create only if file does not exist |
"r" |
Read file |
For writing CSV data, "w" and "a" are the modes you use most often.
Write CSV using pandas
Use pandas when the data is already in a DataFrame.
import pandas as pd
df = pd.DataFrame(
{"name": ["Alice", "Bob"], "age": [30, 25]}
)
df.to_csv("people.csv", index=False)The pandas to_csv documentation writes a DataFrame to a comma-separated values file. For simple list or dictionary rows, the built-in csv module is enough. See pandas DataFrame for table basics.
Read CSV file in Python
This page focuses on writing CSV files. For reading:
- Use
csv.reader()for basic row-by-row reading - Use
pandas.read_csv()for DataFrame workflows
import csv
import tempfile
from pathlib import Path
path = Path(tempfile.mkdtemp()) / "sample.csv"
path.write_text("name,age\nAlice,30\n", encoding="utf-8")
with path.open(newline="", encoding="utf-8") as file:
for row in csv.reader(file):
print(row)Common mistakes when writing CSV in Python
- Forgetting
newline="" - Using
"w"when append mode"a"is needed - Writing the header again every time in append mode
- Manually joining values with commas
- Not using
csv.writerfor fields containing commas or quotes - Passing a flat list to
writerows() - Forgetting
encoding="utf-8" - Calling
close()inside awithblock unnecessarily - Thinking the CSV file must already exist before writing with
"w" - Using pandas for simple CSV writing when
csv.writeris enough - Using NumPy for beginner CSV writing
- Confusing
read_csv()withto_csv() - Leading with read-heavy content when the task is writing CSV data
- Not catching
FileNotFoundErrororPermissionErrorwhen paths come from users—wrap opens in try / except when failure should not crash the whole job
Summary
Use csv.writer() for list or tuple rows. Use writerow() for one row and writerows() for many rows. Use DictWriter for dictionary rows. Open CSV files with newline="" and usually encoding="utf-8". Use df.to_csv() only when working with pandas DataFrames.

