How to Write a CSV File in Python
If you want to save table-like data in Python, a CSV file is a common choice.
A CSV file stores data in rows and columns. Python includes a built-in csv module that makes writing CSV files much easier and safer than building the text yourself.
This page shows you how to:
- Create a new CSV file in Python
- Write one row or many rows
- Use the built-in
csvmodule - Understand when to use
csv.writer()andcsv.DictWriter()
Quick answer #
import csv
rows = [
["name", "age", "city"],
["Alice", 30, "London"],
["Bob", 25, "Paris"]
]
with open("people.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerows(rows)
Use newline="" when opening the file. This helps prevent extra blank lines in CSV output.
The simplest way to write a CSV file #
The basic steps are:
- Import the
csvmodule - Open the file in write mode using
"w" - Use
newline=""when opening the file - Create a writer with
csv.writer(file) - Write rows with
writer.writerow()orwriter.writerows()
Example:
import csv
with open("people.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(["name", "age", "city"])
writer.writerow(["Alice", 30, "London"])
writer.writerow(["Bob", 25, "Paris"])
This creates a file named people.csv.
Its contents will look like this:
name,age,city
Alice,30,London
Bob,25,Paris
If you are not sure how open() works, see the Python open() function explained. For a broader overview of CSV tools, see the Python csv module overview.
Write one row at a time #
Use writer.writerow() when you want to write a single row.
This is useful when:
- You are building rows inside a loop
- You only need to add one line at a time
- Your data is not stored in one big list yet
Each list becomes one row in the CSV file.
Example:
import csv
names = ["Alice", "Bob", "Cara"]
with open("names.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(["name"])
for name in names:
writer.writerow([name])
Important detail:
writer.writerow()expects one row- That row is usually a list or tuple
For example, this is correct:
writer.writerow(["Alice", 30, "London"])
A common beginner mistake is passing a plain value instead of a list.
Write many rows at once #
Use writer.writerows() when you already have a list of rows.
Each inner list becomes one CSV row.
Example:
import csv
rows = [
["name", "age", "city"],
["Alice", 30, "London"],
["Bob", 25, "Paris"],
["Cara", 28, "Berlin"]
]
with open("people.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerows(rows)
This is a good choice for small, ready-made datasets.
Use:
writerow()for one rowwriterows()for multiple rows
Write CSV files with column names #
Use csv.DictWriter() when your data is stored as dictionaries.
This is helpful when:
- Your data has named fields like
"name"and"age" - You want to control the column order
- You want cleaner code when working with structured data
Set fieldnames to choose the column order, then call writeheader() to write the first row.
Example:
import csv
rows = [
{"name": "Alice", "age": 30, "city": "London"},
{"name": "Bob", "age": 25, "city": "Paris"}
]
with open("people.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=["name", "age", "city"])
writer.writeheader()
writer.writerows(rows)
This creates:
name,age,city
Alice,30,London
Bob,25,Paris
Why use DictWriter()?
- The column names are clear
- You do not need to remember the position of each value
- You control the output order with
fieldnames
Important file options to use #
When writing CSV files, these options matter:
encoding="utf-8"for text datanewline=""for CSV files"w"to overwrite an existing file"a"to add rows instead of replacing the file
Example using append mode:
import csv
new_row = ["Dana", 31, "Rome"]
with open("people.csv", "a", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(new_row)
This adds a row to the end of the file instead of replacing it.
If you want to learn more about appending, see how to append to a file in Python.
Common problems beginners run into #
Here are the most common mistakes when writing CSV files:
- Forgetting to
import csv - Opening the file without
newline="" - Using
"w"when you meant to append with"a" - Passing a plain value instead of a list to
writerow() - Using
DictWriterwithout matchingfieldnames
Extra blank lines #
If your CSV file has blank lines between rows, the usual cause is missing newline="".
Wrong:
with open("people.csv", "w", encoding="utf-8") as file:
writer = csv.writer(file)
Correct:
with open("people.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
Badly formatted rows #
Do not build CSV lines yourself with commas like this:
name = "Alice"
age = 30
line = name + "," + str(age)
This may break if values contain commas or quotes.
Use the csv module instead.
DictWriter key problems #
With csv.DictWriter(), the dictionary keys should match the fieldnames.
Example:
import csv
row = {"name": "Alice", "age": 30, "country": "UK"}
with open("people.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=["name", "age", "city"])
writer.writeheader()
writer.writerow(row)
This can cause problems because "country" does not match "city".
Overwriting your data #
If you open a file with "w", Python replaces the file contents.
Use "a" if you want to keep the old data and add new rows.
When not to use this method #
This method is a good beginner-friendly choice, but not every approach is a good idea.
Avoid manually joining values with commas for real CSV work.
Why?
- Values may contain commas
- Values may contain quotes
- CSV escaping rules can be tricky
Use the csv module when values may contain commas or quotes.
For advanced data analysis, a library like pandas can be easier, but beginners usually do not need it just to create a CSV file.
Debugging tips #
If your code is not working, these quick checks can help:
print(rows)
print(type(rows))
print(type(rows[0]))
print(file.name)
import os
print(os.path.exists("people.csv"))
These checks help you answer questions like:
- Is
rowsreally a list? - Is each row a list or dictionary?
- What file name are you writing to?
- Was the file actually created?
If you need to check whether the file exists, see how to check if a file exists in Python.
FAQ #
How do I write a header row in a CSV file? #
With csv.writer(), write the header as the first row.
writer.writerow(["name", "age", "city"])
With csv.DictWriter(), use writeheader().
writer.writeheader()
Why are there blank lines in my CSV file? #
Usually because the file was not opened with newline="".
What is the difference between writerow() and writerows()? #
writerow()writes one rowwriterows()writes multiple rows
Should I use csv.writer() or csv.DictWriter()? #
Use:
csv.writer()for listscsv.DictWriter()for dictionaries with named columns