Python Create CSV File Example Tutorial

Hi Guys,
This tutorial will provide an example of how to create a CSV file in Python. You’ll learn with a simple example showing how to write and save data to a CSV file in Python 3 using built-in modules. If you're looking for a Python writing CSV file example, you're in the right place.
We will generate a demo.csv file containing fields like ID, Name, and Email. The tools we'll use include open()
, csv.writer()
, writerow()
, writerows()
, and close()
. Here's why they’re important:
1. open(): Creates a CSV file if it doesn't already exist.
2. writer(): Generates a CSV writer object to handle writing.
3. writerow(): Writes a single row (usually the header).
4. writerows(): Writes multiple rows from a list of data.
5. close(): Safely closes the file after writing is complete.
Let’s walk through a simple example to understand this better:
Example 1:
main.pyimport csv # open the file in the write mode f = open('demo.csv', 'w') # create the csv writer writer = csv.writer(f) header = ['ID', 'Name', 'Email'] data = [ [1, 'Bhavesh Sonagra', 'bhavesh@gmail.com'], [2, 'Nikhil Patel', 'nikhil@gmail.com'], [3, 'Piyush Kamani', 'piyush@gmail.com'] ] # write the header writer.writerow(header) # write a row to the csv file writer.writerows(data) # close the file f.close()Output

It will help you....
Frequently Asked Questions (FAQ)
How do I create a CSV file in Python?
You can use Python's built-in csv
module to create a CSV file by opening a file in write mode, then using csv.writer()
to write headers and rows.
What is the difference between writerow() and writerows()?
writerow()
writes a single row to the CSV file, while writerows()
writes multiple rows from a list or iterable.
Do I need to install any library to create CSV files in Python?
No, the csv
module is built into Python, so you don’t need to install anything separately.
Can I append data to an existing CSV file?
Yes, by opening the file in 'a'
(append) mode instead of 'w'
(write) mode, you can add new data without overwriting the file.