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)
Please Login to comment...