Open In App

Writing CSV files in Python

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
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.

Python3




# 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.

Python3




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.

Python3




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.

Python3




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.

Python3




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.

Python3




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





Last Updated : 15 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads