How To Create A Csv File Using Python
Last Updated :
22 Feb, 2024
CSV stands for comma-separated values, it is a type of text file where information is separated by commas (or any other delimiter), they are commonly used in databases and spreadsheets to store information in an organized manner. In this article, we will see how we can create a CSV file using Python.
Create a Csv File Using Python
Below are some of the ways by which we can create a CSV file using Python:
- Using Python CSV Module
- Using Pandas Library
- Using plain text file writing
Using Python CSV Module
Now, Python provides a CSV module to work with CSV files, which allows Python programs to create, read, and manipulate tabular data in the form of CSV, This 'CSV' module provides many functions and classes for working with CSV files, It includes functions for reading and writing CSV data, as well as classes like csv.reader and csv.writer for more advanced operations.
Python3
# importing csv
import csv
# Data
data = [
['Name', 'Age', 'City'],
['Aman', 28, 'Pune'],
['Poonam', 24, 'Jaipur'],
['Bobby', 32, 'Delhi']
]
# File path for the CSV file
csv_file_path = 'example.csv'
# Open the file in write mode
with open(csv_file_path, mode='w', newline='') as file:
# Create a csv.writer object
writer = csv.writer(file)
# Write data to the CSV file
writer.writerows(data)
# Print a confirmation message
print(f"CSV file '{csv_file_path}' created successfully.")
Output:

Using Pandas Library
Pandas is a powerful Python library widely used for data manipulation and analysis, now Pandas also offers methods for converting data into CSV format and writing it to a file. In this example, we are using Pandas to create and edit CSV files in Python.
Python3
# Step 1 Importing pandas
import pandas as pd
# Step 2 Prepare your data
data = {
'Name': ['Rajat', 'Tarun', 'Bobby'],
'Age': [30, 25, 35],
'City': ['New York', 'Delhi', 'Pune']
}
# Step 3 Create a DataFrame using DataFrame function
df = pd.DataFrame(data)
# Step 4 Specify the file path to save data
csv_file_path = 'data.csv'
# Step 5 Write the DataFrame to a CSV file using to_csv() function where file path is passed
df.to_csv(csv_file_path, index=False)
print(f'CSV file "{csv_file_path}" has been created successfully.')
Output:
File Creation ScreenshotNote: Ignore the deprecation warning message.
Csv File Output:
csv fileUsing Plain Text File Writing
We can manually write data to a CSV file using basic file writing operations. While it is less common and less convenient than using the csv module or pandas, it's still possible and can be done.
Python3
# data to be stored in csv in form of list of list
data = [
['Name', 'Gender', 'Age', 'Course'],
['Aman', 'M', 22, 'B.Tech'],
['Pankaj', 'M', 24, 'M.Tech'],
['Beena', 'F', '23', 'MBA']
]
# file path of csv to be stored
csv_file_path = 'ex3.csv'
# opening file in write mode using a context manager
with open(csv_file_path, mode='w') as file:
for row in data:
file.write(','.join(map(str, row)) + '\n') # writing data row by row
print(f"CSV file '{csv_file_path}' created successfully!!!")
Output:
csv file
Similar Reads
How to Add Numbers in a Csv File Using Python When working with CSV files in Python, adding numbers in the CSV file is a common requirement. This article will guide you through the process of adding numbers within a CSV file. Whether you're new to data analysis or an experienced practitioner, understanding this skill is vital for efficient data
3 min read
Convert CSV to JSON using Python Converting CSV to JSON using Python involves reading the CSV file, converting each row into a dictionary and then saving the data as a JSON file. For example, a CSV file containing data like names, ages and cities can be easily transformed into a structured JSON array, where each record is represent
2 min read
How to Append Data in Excel Using Python We are given an Excel file and our task is to append the data into this excel file using Python. In this article, we'll explore different approaches to append data to an Excel file using Python. Append Data in Excel Using PythonBelow, are some examples to understand how to append data in excel using
2 min read
How to Create a Python Dictionary from Text File? The task of creating a Python dictionary from a text file involves reading its contents, extracting key-value pairs and storing them in a dictionary. Text files typically use delimiters like ':' or ',' to separate keys and values. By processing each line, splitting at the delimiter and removing extr
3 min read
How to Convert Tab-Delimited File to Csv in Python? We are given a tab-delimited file and we need to convert it into a CSV file in Python. In this article, we will see how we can convert tab-delimited files to CSV files in Python. Convert Tab-Delimited Files to CSV in PythonBelow are some of the ways to Convert Tab-Delimited files to CSV in Python: U
2 min read