In this article, we will learn to write CSV files using Python. CSV(Comma Separated Valued) file is a file format that stores the data in tabular form. In a CSV file, commas separate the fields and the file line contains the data record.
We will use the built-in module
csv
to work CSV files in Python. Here, we use the following two classes of this
csv
module to write CSV files:
- Writing files using the Python class
csv.writer
- Writing files using the Python class
csv.DictWriter
Writing files using the Python class
csv.writer
It provides two methods(
writerow()
and
writerows()
) to write CSV files. Method
writerow()
writes a single row at a time and
writerows()
writes multiple rows at a time.
We will follow the below steps for writing CSV files:
- Import
csv
module. - Set headers and data.
- Open the CSV file in write mode.
- Create an object by calling the class
writer
of the modulecsv
. - Use
writerow
function for writing headers and using the functionwriterows()
for writing data.
The example of the code for CSV writing:
1 2 3 4 5 6 7 8 9 10 11 12 13 | import csv headers = ['Name', 'Mobile', 'Email'] data = [ ['Tom', '1234567891', 'tom@test.com'], ['Vicky', '9988776655', 'vicky@test.com'], ['Tropsal', '7766554433', 'troposal@test.com'], ['Mahesh', '7464646463', 'mahesh@test.com'] ] #open the csv file in write mode with open('users.csv', mode='w') as csv_file: csv_writer = csv.writer(csv_file) csv_writer.writerow(headers) csv_writer.writerows(data) |
You can check the python CSV file writing code using the module
csv
on GitHub also.
Writing files using the Python class
csv.DictWriter
It is used to write dictionary-mapped data in the CSV file.
The following are steps for writing files using class
csv.DictWriter
- Import
csv
module. - Set headers and data in dictionary mapping.
- Open the CSV file in write mode.
- Create an object by calling the class
DictWriter
of the modulecsv
. - Use
writeheader
function for writing headers and usewriterows()
function for writing data.
An example of the code for writing CSV:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import csv headers = ['Name', 'Mobile', 'Email'] data = [ {'Name': 'Tom Jerry', 'Mobile': '1234567891', 'Email': 'tom@test.com'}, {'Name': 'Vicky', 'Mobile': '9988776655', 'Email': 'vicky@test.com'}, {'Name': 'Tropsal', 'Mobile': '7766554433', 'Email': 'troposal@test.com'}, {'Name': 'Mahesh', 'Mobile': '7464646463', 'Email': 'mahesh@test.com'} ] #open the csv file in write mode with open('users.csv', mode='w') as csv_file: csv_writer = csv.DictWriter(csv_file, fieldnames = headers) #Header writing csv_writer.writeheader() csv_writer.writerows(data) |
You can check Python CSV file writing using
csv
module and DictWriter method on GitHub