How to Create a CSV File in Python?

Recently, while working on a data analytics project, I needed to generate daily sales reports from an e-commerce platform. The requirement was to store transaction details in a structured format. Since CSV files are widely used for data exchange and compatibility with spreadsheets and databases. In this tutorial, I will explain how to create a CSV file in Python with detailed examples.

Create a CSV File in Python

CSV stands for Comma-Separated Values. It is a simple file format used to store tabular data, such as a spreadsheet or database. Each line in a CSV file corresponds to a row in the table, and each value is separated by a comma. CSV files are widely used because they are easy to read and write, and they are compatible with most software applications.

Read How to Write Bytes to File in Python?

1. Use the csv Module

The csv module in Python provides functionality to both read from and write to CSV files. Let’s start with a basic example where we create a CSV file containing information about a group of people.

Step-by-Step Guide

  1. Import the CSV Module:
import csv
  1. Define the Data: Let’s create a list of dictionaries, each representing a person with their name, age, and city.
people = [
       {"Name": "John Doe", "Age": 28, "City": "New York"},
       {"Name": "Jane Smith", "Age": 34, "City": "Los Angeles"},
       {"Name": "Emily Davis", "Age": 22, "City": "Chicago"}
]
  1. Specify the CSV File Path: Choose a location and a name for your CSV file.
csv_file = "people.csv"
  1. Write Data to CSV File: Use the csv.DictWriter class to write the data.
with open(csv_file, mode='w', newline='') as file:
    writer = csv.DictWriter(file, fieldnames=["Name", "Age", "City"])
    writer.writeheader()
    for person in people:
        writer.writerow(person)

Explanation

  • csv.DictWriter: This class operates like a regular writer but maps dictionaries onto output rows.
  • writeheader: Writes the field names (header row) to the CSV file.
  • writerow: Writes each dictionary (row) to the CSV file.

I executed the above example code and added the screenshot below.

Create a CSV File in Python

By following these steps, you will have created a CSV file named people.csv in your specified directory.

Check out How to Read Large CSV Files in Python?

2. Use pandas

The pandas library offers a more flexible and powerful way to handle CSV files. It is particularly useful for larger datasets and more complex operations.

Step-by-Step Guide

  1. Import the Pandas Library:
import pandas as pd
  1. Define the Data: Create a dictionary where the keys are column names and the values are lists of column data.
data = {
       "Name": ["John Doe", "Jane Smith", "Emily Davis"],
       "Age": [28, 34, 22],
       "City": ["New York", "Los Angeles", "Chicago"]
}
  1. Create a DataFrame: Convert the dictionary into a pandas DataFrame.
df = pd.DataFrame(data)
  1. Write Data to CSV File: Use the to_csv method to write the DataFrame to a CSV file.
df.to_csv("people_pandas.csv", index=False)

Explanation

  • pd.DataFrame: Converts the dictionary into a DataFrame, a two-dimensional, size-mutable, and potentially heterogeneous tabular data structure.
  • to_csv: Writes the DataFrame to a CSV file. The index=False parameter prevents pandas from writing row indices.

I executed the above example code and added the screenshot below.

How to Create a CSV File in Python

Using pandas simplifies the process and provides additional functionalities such as handling missing data, merging datasets, and more.

Read How to Create a Python File in Terminal?

Conclusion

In this tutorial, I have explained how to create a CSV file in Python. I discussed a step-by-step guide and explanation to create a CSV file by using csv module and using pandas.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.