The Wayback Machine - https://web.archive.org/web/20240710231313/https://www.geeksforgeeks.org/writing-csv-files-in-python/
Open In App

Writing CSV files in Python

Last Updated : 20 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format. Let’s discuss How to Write to CSV Files in Python.

Writing CSV files in Python

Below are the ways by which we can write CSV files in Python:

  • Write into CSV files using Python csv.DictWriter()
  • Write into CSV files using csv.writer()
    • Write CSV File Having Pipe Delimiter
    • Write CSV files with quotes
    • Writing CSV files with custom quoting character
    • Using escapechar in CSV writer

Python Write to CSV using DictWriter()

This class returns a writer object which maps dictionaries onto output rows.

Syntax: csv.DictWriter(csvfile, fieldnames, restval=”, extrasaction=’raise’, dialect=’excel’, *args, **kwds)

Parameters:

  • csvfile: A file object with write() method.
  • fieldnames: A sequence of keys that identify the order in which values in the dictionary should be passed.
  • restval (optional): Specifies the value to be written if the dictionary is missing a key in fieldnames.
  • extrasaction (optional): If a key not found in fieldnames, the optional extrasaction parameter indicates what action to take. If it is set to raise a ValueError will be raised.
  • dialect (optional): Name of the dialect to be used.

In this example, student records are stored as dictionaries, and a CSV file named “university_records.csv” is generated using these dictionaries. The `csv.DictWriter` class is utilized to write the field names as headers and the dictionary data rows to the CSV file.

Python
# importing the csv module
import csv

# my data rows as dictionary objects
mydict = [{'branch': 'COE', 'cgpa': '9.0', 'name': 'Nikhil', 'year': '2'},
          {'branch': 'COE', 'cgpa': '9.1', 'name': 'Sanchit', 'year': '2'},
          {'branch': 'IT', 'cgpa': '9.3', 'name': 'Aditya', 'year': '2'},
          {'branch': 'SE', 'cgpa': '9.5', 'name': 'Sagar', 'year': '1'},
          {'branch': 'MCE', 'cgpa': '7.8', 'name': 'Prateek', 'year': '3'},
          {'branch': 'EP', 'cgpa': '9.1', 'name': 'Sahil', 'year': '2'}]

# field names
fields = ['name', 'branch', 'year', 'cgpa']

# name of csv file
filename = "university_records.csv"

# writing to csv file
with open(filename, 'w') as csvfile:
    # creating a csv dict writer object
    writer = csv.DictWriter(csvfile, fieldnames=fields)

    # writing headers (field names)
    writer.writeheader()

    # writing data rows
    writer.writerows(mydict)

Output:

name,branch,year,cgpa
Nikhil,COE,2,9.0
Sanchit,COE,2,9.1
Aditya,IT,2,9.3
Sagar,SE,1,9.5
Prateek,MCE,3,7.8
Sahil,EP,2,9.1

Write into CSV Files Using csv.writer()

csv.writer class is used to insert data to the CSV file. This class returns a writer object which is responsible for converting the user’s data into a delimited string. A csvfile object should be opened with newline='' otherwise, newline characters inside the quoted fields will not be interpreted correctly.

Syntax: csv.writer(csvfile, dialect=’excel’, **fmtparams)

Parameters:

  • csvfile: A file object with write() method.
  • dialect (optional): Name of the dialect to be used.
  • fmtparams (optional): Formatting parameters that will overwrite those specified in the dialect.

In this example, a CSV file named “university_records.csv” is created and populated with student records. The file contains fields such as Name, Branch, Year, and CGPA. The data rows for individual students are written to the CSV file, followed by the field names.

Python
import csv

# field names
fields = ['Name', 'Branch', 'Year', 'CGPA']

# data rows of csv file
rows = [['Nikhil', 'COE', '2', '9.0'],
        ['Sanchit', 'COE', '2', '9.1'],
        ['Aditya', 'IT', '2', '9.3'],
        ['Sagar', 'SE', '1', '9.5'],
        ['Prateek', 'MCE', '3', '7.8'],
        ['Sahil', 'EP', '2', '9.1']]

# name of csv file
filename = "university_records.csv"

# writing to csv file
with open(filename, 'w') as csvfile:
    # creating a csv writer object
    csvwriter = csv.writer(csvfile)

    # writing the fields
    csvwriter.writerow(fields)

    # writing the data rows
    csvwriter.writerows(rows)

Output:

Name,Branch,Year,CGPA
Nikhil,COE,2,9.0
Sanchit,COE,2,9.1
Aditya,IT,2,9.3
Sagar,SE,1,9.5
Prateek,MCE,3,7.8
Sahil,EP,2,9.1

Creating CSV Files in Python Having Pipe Delimiter

In this example, a CSV file named “data_pipe_delimited.csv” is generated with data rows separated by pipe (|) delimiters. The file contains information on individuals’ names, ages, and cities.

Python
import csv

# Define the data to be written to the CSV file
data = [
    ['Name', 'Age', 'City'],
    ['Alice', 25, 'New York'],
    ['Bob', 30, 'Los Angeles'],
    ['Charlie', 35, 'Chicago']
]

# Specify the file name
filename = 'data_pipe_delimited.csv'

# Write data to the CSV file with a pipe delimiter
with open(filename, 'w', newline='') as csvfile:
    csvwriter = csv.writer(csvfile, delimiter='|')
    csvwriter.writerows(data)

print(f"Data has been written to {filename}")

Output:

Name|Age|City
Alice|25|New York
Bob|30|Los Angeles
Charlie|35|Chicago


Write CSV Files with Quotes

In this example, a CSV file named “students_data.csv” is generated with each field enclosed in double quotes. The file contains information about students’ names, branches, years, and CGPA scores.

Python
import csv

# Define the rows data
rows = [
    ['Nikhil', 'COE', '2', '9.0'],
    ['Sanchit', 'COE', '2', '9.1'],
    ['Aditya', 'IT', '2', '9.3'],
    ['Sagar', 'SE', '1', '9.5'],
    ['Prateek', 'MCE', '3', '7.8'],
    ['Sahil', 'EP', '2', '9.1']
]

# Specify the file name
filename = 'students_data.csv'

# Write the rows data to the CSV file with quotes around each field
with open(filename, 'w', newline='') as csvfile:
    csvwriter = csv.writer(csvfile, quoting=csv.QUOTE_ALL)
    csvwriter.writerows(rows)

print(f"Data has been written to {filename}")

Output:

"Nikhil","COE","2","9.0"
"Sanchit","COE","2","9.1"
"Aditya","IT","2","9.3"
"Sagar","SE","1","9.5"
"Prateek","MCE","3","7.8"
"Sahil","EP","2","9.1"



Writing CSV Files with Custom Quoting Character

In this example, a CSV file named “students_data.csv” is created with fields separated by pipe (|) delimiters and enclosed in tildes (~). The data includes student names, branches, years, and CGPA scores.

Python
import csv

rows = [
    ['Nikhil', 'COE', '2', '9.0'],
    ['Sanchit', 'COE', '2', '9.1'],
    ['Aditya', 'IT', '2', '9.3'],
    ['Sagar', 'SE', '1', '9.5'],
    ['Prateek', 'MCE', '3', '7.8'],
    ['Sahil', 'EP', '2', '9.1']
]

filename = 'students_data.csv'

with open(filename, 'w', newline='') as file:
    writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC,
                        delimiter='|', quotechar='~')
    writer.writerows(rows)

print(f"Data has been written to {filename}")

Output:

~Nikhil~|~COE~|~2~|9.0
~Sanchit~|~COE~|~2~|9.1
~Aditya~|~IT~|~2~|9.3
~Sagar~|~SE~|~1~|9.5
~Prateek~|~MCE~|~3~|7.8
~Sahil~|~EP~|~2~|9.1



Using escapechar in CSV

In this example, a CSV file named “students.csv” is generated with fields separated by pipe (|) delimiters. The quotechar is set to double quotes (") and the escapechar is set to backslash (\\), allowing for proper handling of quotes within the data.

Python
import csv

rows = [
    ['Nikhil', 'COE', '2', '9.0'],
    ['Sanchit', 'COE', '2', '9.1'],
    ['Aditya', 'IT', '2', '9.3'],
    ['Sagar', 'SE', '1', '9.5'],
    ['Prateek', 'MCE', '3', '7.8'],
    ['Sahil', 'EP', '2', '9.1']
]

filename = 'students.csv'

with open(filename, 'w', newline='') as file:
    writer = csv.writer(file, quoting=csv.QUOTE_NONE,
                        delimiter='|', quotechar='"', escapechar='\\')
    writer.writerows(rows)

print(f"Data has been written to {filename}")

Output:

Nikhil|COE|2|9.0
Sanchit|COE|2|9.1
Aditya|IT|2|9.3
Sagar|SE|1|9.5
Prateek|MCE|3|7.8
Sahil|EP|2|9.1

Writing CSV files in Python – FAQs

How to export a CSV file in Python?

To export (or write) data to a CSV file in Python, you typically use the csv module. Here’s a basic example:

import csv

data = [
['Name', 'Age', 'City'],
['John Doe', 30, 'New York'],
['Jane Smith', 25, 'Los Angeles'],
['Bob Johnson', 45, 'Chicago']
]

# Specify the file path where you want to export the CSV file
file_path = 'output.csv'

# Write data to CSV file
with open(file_path, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(data)

print(f'CSV file exported successfully to {file_path}')

How to write and append a CSV file in Python?

You can write and append to a CSV file using the csv module. To append data, open the file in append mode ('a') instead of write mode ('w'):

import csv

# Data to append
new_data = [
['Alice Brown', 35, 'Boston'],
['Eve Green', 28, 'San Francisco']
]

file_path = 'output.csv'

# Append data to CSV file
with open(file_path, 'a', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(new_data)

print(f'New data appended to CSV file {file_path}')

How to write a CSV file from a text file in Python?

To write a CSV file from a text file in Python, you typically read the text file line by line and then write each line to the CSV file. Here’s a basic example:

import csv

text_file_path = 'input.txt'
csv_file_path = 'output.csv'

# Read lines from text file
with open(text_file_path, 'r') as infile:
lines = infile.readlines()

# Write lines to CSV file
with open(csv_file_path, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
for line in lines:
writer.writerow([line.strip()])

print(f'CSV file created from text file {text_file_path} at {csv_file_path}')

How to write dict to CSV in Python?

You can write a dictionary to a CSV file in Python using the csv.DictWriter class. Here’s an example:

import csv

data = [
{'Name': 'John Doe', 'Age': 30, 'City': 'New York'},
{'Name': 'Jane Smith', 'Age': 25, 'City': 'Los Angeles'},
{'Name': 'Bob Johnson', 'Age': 45, 'City': 'Chicago'}
]

file_path = 'output_dict.csv'

# Write dictionary to CSV file
with open(file_path, 'w', newline='') as csvfile:
fieldnames = ['Name', 'Age', 'City']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(data)

print(f'Dictionary data exported to CSV file {file_path}')

How data can be read from CSV file in Python?

To read data from a CSV file in Python, use the csv.reader or csv.DictReader class from the csv module. Here’s a basic example using csv.reader:

import csv

file_path = 'input.csv'

# Read data from CSV file
with open(file_path, 'r') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)

For reading into dictionaries, use csv.DictReader:

import csv

file_path = 'input_dict.csv'

# Read data from CSV file into dictionaries
with open(file_path, 'r') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row)


Similar Reads

Reading and Writing CSV Files in Python
CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. It is one of the most common methods for exchanging data between applications and popular data format used in Data Science. It is supported by a wide range of applications. A CSV file stores tabular data in which each data field is separa
4 min read
How to create multiple CSV files from existing CSV file using Pandas ?
In this article, we will learn how to create multiple CSV files from existing CSV file using Pandas. When we enter our code into production, we will need to deal with editing our data files. Due to the large size of the data file, we will encounter more problems, so we divided this file into some small files based on some criteria like splitting in
3 min read
Python program to read CSV without CSV module
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the nam
3 min read
Writing data from a Python List to CSV row-wise
Comma Separated Values (CSV) files a type of a plain text document in which tabular information is structured using a particular format. A CSV file is a bounded text format which uses a comma to separate values. The most common method to write data from a list to CSV file is the writerow() method of writer and DictWriter class. Example 1: Creating
2 min read
Convert multiple JSON files to CSV Python
In this article, we will learn how to convert multiple JSON files to CSV file in Python. Before that just recall some terms : JSON File: A JSON file may be a file that stores simple data structures and objects in JavaScript Object Notation (JSON) format, which may be a standard data interchange format. It is primarily used for transmitting data bet
8 min read
How to merge two csv files by specific column using Pandas in Python?
In this article, we are going to discuss how to merge two CSV files there is a function in pandas library pandas.merge(). Merging means nothing but combining two datasets together into one based on common attributes or column. Syntax: pandas.merge() Parameters : data1, data2: Dataframes used for merging.how: {‘left’, ‘right’, ‘outer’, ‘inner’}, def
3 min read
How to read numbers in CSV files in Python?
Prerequisites: Reading and Writing data in CSV, Creating CSV files CSV is a Comma-Separated Values file, which allows plain-text data to be saved in a tabular format. These files are stored in our system with a .csv extension. CSV files differ from other spreadsheet file types (like Microsoft Excel) because we can only have a single sheet in a file
4 min read
Getting all CSV files from a directory using Python
Python provides many inbuilt packages and modules to work with CSV files in the workspace. The CSV files can be accessed within a system's directories and subdirectories and modified or edited. The CSV file contents can both be printed on the shell, or it can be saved in the form of the dataframe and played with later. In this article, we will see
3 min read
Working with csv files in Python
Python is one of the important fields for data scientists and many programmers to handle a variety of data. CSV (Comma-Separated Values) is one of the prevalent and accessible file formats for storing and exchanging tabular data. In article explains What is CSV. Working with CSV files in Python, Reading, and Writing to a CSV file, and Storing Email
9 min read
Read multiple CSV files into separate DataFrames in Python
Sometimes you might need to read multiple CSV files into separate Pandas DataFrames. Importing CSV files into DataFrames helps you work on the data using Python functionalities for data analysis. In this article, we will see how to read multiple CSV files into separate DataFrames. For reading only one CSV file, we can use pd.read_csv() function of
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg