Write CSV in Python

Learn how to write CSV files in Python using the built-in csv module. See examples with csv.writer, writerow(), writerows(), headers, append mode, DictWriter, custom delimiters, newline handling, and pandas to_csv().

Published

Updated

Read time 6 min read

Reviewed byDeepak Prasad

Write CSV in Python

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().

python
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])
Output

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.

python
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"))
Output

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.

python
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"))
Output

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.

python
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"))
Output

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.

python
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"))
Output

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.

python
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"))
Output

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.

python
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"))
Output

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.

python
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"))
Output

Use quoting=csv.QUOTE_ALL when every field should be quoted.


Write CSV with encoding

Use UTF-8 for most modern files.

python
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"])
Output

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="".

python
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")))
Output

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.

python
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
python
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)
Output

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.writer for fields containing commas or quotes
  • Passing a flat list to writerows()
  • Forgetting encoding="utf-8"
  • Calling close() inside a with block unnecessarily
  • Thinking the CSV file must already exist before writing with "w"
  • Using pandas for simple CSV writing when csv.writer is enough
  • Using NumPy for beginner CSV writing
  • Confusing read_csv() with to_csv()
  • Leading with read-heavy content when the task is writing CSV data
  • Not catching FileNotFoundError or PermissionError when 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.


References


Frequently Asked Questions

1. How do you write a CSV file in Python?

Open the file with open(path, "w", newline="", encoding="utf-8"), create csv.writer(file), write a header with writerow() if needed, then write data rows with writerow() or writerows().

2. Why do I get blank lines in my CSV on Windows?

Open CSV files with newline="" when using open(). Without it, Python may write extra blank lines on Windows because of newline translation.

3. What is the difference between writerow() and writerows()?

writerow() writes one row. writerows() writes every row from a list of rows. Do not pass a flat list to writerows().

4. When should I use csv.DictWriter?

Use DictWriter when each row is a dictionary. Set fieldnames, call writeheader(), then write dictionary rows with writerow() or writerows().

5. How do I append rows to an existing CSV file?

Open the file with mode "a" and newline="". Do not write the header again unless you are creating a new file.

6. Should I use pandas to write CSV?

Use the csv module for simple list or dictionary rows. Use pandas DataFrame.to_csv() when your data is already in a DataFrame.
Bashir Alam

Data Analyst and Machine Learning Engineer

Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in OCR, text extraction, data preprocessing, and …