Python CSV Writer Example
This example shows how to write rows to a CSV file in Python with the built-in csv module.
You will create a simple file named people.csv, write a header row and some data rows, and see what the finished file looks like. This is a good starting point if you want to export table-like data from a Python script.
Quick example #
import csv
rows = [
["name", "age", "city"],
["Alice", 25, "London"],
["Bob", 30, "Paris"],
["Charlie", 22, "Berlin"]
]
with open("people.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerows(rows)
print("CSV file written successfully")
Note: Use newline="" when opening the file. This helps avoid blank lines in CSV output on some systems.
What this example does #
- Creates a new CSV file named
people.csv - Writes a header row and several data rows
- Uses Python’s built-in
csvmodule - Shows a simple beginner-friendly way to generate CSV output
If you want a broader explanation of CSV tools in Python, see the Python csv module overview.
How the code works #
Here is the same code again:
import csv
rows = [
["name", "age", "city"],
["Alice", 25, "London"],
["Bob", 30, "Paris"],
["Charlie", 22, "Berlin"]
]
with open("people.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerows(rows)
print("CSV file written successfully")
1. Import csv #
import csv
This imports Python’s built-in CSV module so you can use csv.writer().
If you forget this line, Python will not know what csv means.
2. Store the data as rows #
rows = [
["name", "age", "city"],
["Alice", 25, "London"],
["Bob", 30, "Paris"],
["Charlie", 22, "Berlin"]
]
This is a list of lists:
- Each inner list is one row
- The first row is the header
- The remaining rows are the data
3. Open the file in write mode #
with open("people.csv", "w", newline="", encoding="utf-8") as file:
This line does several important things:
"people.csv"is the file name"w"means write modenewline=""helps prevent extra blank linesencoding="utf-8"is a good default for text fileswith open(...)automatically closes the file when done
If you are new to open(), see Python open() function explained.
4. Create a CSV writer #
writer = csv.writer(file)
This creates a writer object connected to the file.
You use this writer to send rows into the CSV file.
5. Write all rows at once #
writer.writerows(rows)
This writes every row from the rows list into the file.
After that, the file is ready to use.
Expected file content #
After running the script, the file people.csv should contain:
name,age,city
Alice,25,London
Bob,30,Paris
Charlie,22,Berlin
You can open this file in:
- A text editor
- Excel
- Google Sheets
- Other spreadsheet programs
To run the script, you can use:
python your_script.py
Then check the file content with one of these commands:
type people.csv
cat people.csv
Useful beginner variations #
Write one row at a time #
If you want to write rows one by one, use writer.writerow(...) instead of writer.writerows(...).
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", 25, "London"])
writer.writerow(["Bob", 30, "Paris"])
writerow()writes one rowwriterows()writes many rows
If you want a step-by-step guide, see How to write a CSV file in Python.
Change the file name #
You can create a different CSV file by changing the file name:
with open("students.csv", "w", newline="", encoding="utf-8") as file:
Replace the example data #
You can swap the sample rows with your own data:
rows = [
["product", "price", "stock"],
["Pen", 1.5, 100],
["Notebook", 3.0, 50]
]
Write data from another part of your program #
You can build the rows list from:
- User input
- Calculations
- API results
- Data read from another file
If you want to add new rows without replacing the old file, see How to append to a file in Python.
When this example is useful #
This example is helpful when you need to:
- Save simple table data to a file
- Export results from a Python script
- Create spreadsheet-friendly output
- Learn the difference between plain text files and structured CSV files
A matching next step is reading CSV files back into Python. For that, see the Python CSV reader example.
Common mistakes #
Here are some common problems beginners run into.
Forgetting to import csv #
If you use csv.writer() without importing csv, Python will raise an error.
Make sure this line is at the top:
import csv
You can quickly test the module with:
python -c "import csv; print('csv module loaded')"
Opening the file without newline="" #
Without newline="", some systems may create extra blank lines in the CSV output.
Use:
open("people.csv", "w", newline="", encoding="utf-8")
Overwriting an existing file by mistake #
Using "w" replaces the old file content.
If people.csv already exists, it will be overwritten.
Passing the wrong data shape #
This works:
rows = [
["name", "age"],
["Alice", 25]
]
This is not a proper list of rows:
rows = ["name", "age", "Alice", 25]
A CSV writer expects each row to be a separate list or iterable.
Trying to write unsupported custom objects #
CSV files work best with simple values such as:
- Strings
- Integers
- Floats
If you try to write custom objects directly, the output may not be what you expect. Convert values to simple text or numbers first.
File and permission problems #
If Python cannot create or write the file, you may see an error such as:
FAQ #
What is the difference between writerow() and writerows()? #
writerow() writes one row.
writerows() writes multiple rows from a list or other iterable.
Why use newline="" when opening a CSV file? #
It prevents extra blank lines from appearing in the output on some operating systems.
Can I write dictionaries to a CSV file? #
Yes, but that is usually done with csv.DictWriter, which is better covered separately than in this basic example.
Will this overwrite an existing file? #
Yes. Opening a file with "w" replaces the old content. Use append mode if you want to add rows instead.