How To Create CSV File In Python

In this tutorial, we’ll learn how to create a CSV file in Python using the built-in csv module. CSV (Comma Separated Values) is a commonly used data format for storing and exporting tabular data in a simple, plain-text format.

Python provides an easy-to-use module called csv to work with this format.

Step 1: Importing the csv module

First, start by importing the csv module, which comes pre-installed with Python.

Step 2: Prepare the data

Prepare the data that you want to write to the CSV file. Usually, the data is in the form of a list of lists, where each sublist represents a row and its elements represent columns.

For example, let’s work with the following data:

In this example, we have a list containing four lists. The first sublist represents the header row, and the remaining three sublists each represent a single record.

Step 3: Creating and opening the CSV file

To create a CSV file, use the built-in open() function with the appropriate file mode. Here, we are using the 'w' mode to create and open the file in ‘write’ mode. Also, it is advisable to use the newline='' parameter to prevent issues with newline characters in different operating systems.

The with statement is used to open the file and automatically close it once the block of code inside is executed.

Step 4: Writing data to the CSV file

Now, let’s use the csv.writer object to write the data to the CSV file. To write rows to the file, use the .writerow() method and to write multiple rows at once, use the .writerows() method.

That’s it! The entire Python script looks like this:

This will create a file named ‘example.csv’ in the current directory with the following content:

Alice,28,New York
Bob,22,San Francisco
Charles,30,Los Angeles

Make sure to replace ‘example.csv’ with the desired location and name for your CSV file.

Full Code


In this tutorial, we learned how to create a CSV file in Python using the built-in csv module. This is a simple and efficient method for storing and exporting tabular data. With just a few lines of code, you can create and write data to a CSV file in Python.