Menu Close

Write CSV Files in Python

Write CSV files in Python

In this article, you will learn all about How to write CSV files in Python with the help of examples. Here we are going to use a built-in CSV module. In our previous tutorial, we have seen all about reading CSV files in different ways with the help of examples.

Most of the time you need to read or write CSV files using Python, so you can use the Python built-in CSV module that provides approx all the functionality to read or write CSV files with the help of the Python programming language.

In this guide, we will only focus on writing CSV files in different formats with the help of examples.

Python CSV Module

Python provides a built-in module CSV that provides lots of functions and attributes to work ( Read and write ) with CSV file data.

Python CSV module provides a writer() function that is used to write the CSV files. Suppose we want to write a new CSV file with the following data.
Let’s look an example of csv.writer() function to write the csv files.

Suppose we have the following entries and we want to write these content to a CSV file students.csv

id,first_name,last_name,roll_no,course
1,Vishvajit,Rao,12|BCA
2,Shivam,Kumar,13,BTech
3,Shreya,Singh,14,MCA
4,Shivam,Rao,40,PHD

id,first_name,last_name,roll_no,course
1,Vishvajit,Rao,12|BCA
2,Shivam,Kumar,13,BTech
3,Shreya,Singh,14,MCA
4,Shivam,Rao,40,PHD

Example: Write CSV files with csv.writer()

In the above example, we have used csv.writer() function to initialize the write object and use multiple writer.writerow() to write content in the students.csv file.

import csv 
with open('students.csv', 'w') as file:
    writer = csv.writer(file)
    writer.writerow(['id','first_name','last_name','roll_no','course'])
    writer.writerow(['1','Vishvajit','Rao',12,'BCA'])
    writer.writerow(['2','Shivam','Rao',13,'BTech'])
    writer.writerow(['3','Shreya','Singh',14,'MCA'])
    writer.writerow(['4','Shivam','Rao',40,'PHD'])

We have used the Python open() function to open the students.csv file in write mode. When you will run the above code, a students.csv file will create in the current working directory.

Writing multiple rows using writerows() function

Sometimes you need to write multiple rows in a CSV file instead of writing one row at a time like the above example, Then you can use the Python CSV module writerows() function.

Suppose we have the following contents and we want to write these contents inside students.csv file.

Example: Writing multiple rows using writerows()

data = [
    ['ID','First_name','last_name','roll_no','BCA'],
    ['1','Vishvajit','Rao',12,'BCA'],
    ['2','Shivam','Singh',13,'BA'],
    ['3','Shreya','Kumari',14,'MCA'],
    ['4','Vinay','kumar',15,'BCA']

]

import csv 
with open('students.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(data)

Output

ID,First_name,last_name,roll_no,BCA
1,Vishvajit,Rao,12,BCA
2,Shivam,Singh,13,BA
3,Shreya,Kumari,14,MCA
4,Vinay,kumar,15,BCA

Write CSV Files with Custom Delimiters

By default, a comma is used as a delimiter in a CSV file. However, some CSV files can use delimiters other than a comma.

Suppose we want to use another delimiter pipe ( | ) rather than a comma, Then we have to use pass an additional parameter delimiter to the csv.writer() function.

Example: Writing CSV file with custom delimiter

import csv 

data = [["id","first_name","last_name","roll_no","course"],
	[1,"Vishvajit","Rao",12,"BCA"],
	[2,"Shivam","Kumar",13,"BTech"],
	[3,"Shreya","Singh",14,"MCA"],
	[4,"Shivam","Rao",4,"PHD"]]

with open('students.csv', 'w', newline='') as file:
    writer = csv.writer(file, delimiter='|')
    writer.writerows(data)

Output

id|first_name|last_name|roll_no|course
1|Vishvajit|Rao|12|BCA
2|Shivam|Kumar|13|BTech
3|Shreya|Singh|14|MCA
4|Shivam|Rao|4|PHD

As you can see in the above example, to use custom delimiter pipe ( | ) in the students.csv file, we have passed an additional parameter delimeter = ‘|’.This parameter tells the writer object that the CSV file should have | as a delimiter.

Write CSV files with Quotes

Some CSV files have quotes around each of the items. To write that type of CSV file we have to use quoting parameter in csv.writer() function.

Example: Write CSV file with quotes

import csv 

data = [["id","first_name","last_name","roll_no","course"],
	[1,"Vishvajit","Rao",12,"BCA"],
	[2,"Shivam","Kumar",13,"BTech"],
	[3,"Shreya","Singh",14,"MCA"],
	[4,"Shivam","Rao",4,"PHD"]]

with open('students.csv', 'w', newline='') as file:
    writer = csv.writer(file, delimiter=';', quoting=csv.QUOTE_ALL)
    writer.writerows(data)

Output

"id";"first_name";"last_name";"roll_no";"course"
"1";"Vishvajit";"Rao";"12";"BCA"
"2";"Shivam";"Kumar";"13";"BTech"
"3";"Shreya";"Singh";"14";"MCA"
"4";"Shivam";"Rao";"4";"PHD"

There are four constants provided by the Python CSV module that can be pass to the quoting parameter.

  • csv.QUOTE_ALL:- Instruct writer object to quotes all fields.
  • csv.QUOTE_MINIMAL:- Instruct writer object to quotes only those fields who contains special characters.
  • csv.QUOTE_NONE:- Instruct writer object to not use any quotes arround the each entries.
  • csv.QUOTE_NONNUMERIC:- Instruct writer object to quotes only non numeric value.

Write CSV file with custom quoting characters

We can also write CSV files with custom quoting characters. To perform this operation we have another parameter quotechar.

let’s see look at an example to write a CSV file with custom quoting characters. In this example, we will write a CSV file in which each of the strings is enclosed between asterisk ( * ).

Example:- Writing CSV file with custom quote char

import csv 

data = [["id","first_name","last_name","roll_no","course"],
	[1,"Vishvajit","Rao",12,"BCA"],
	[2,"Shivam","Kumar",13,"BTech"],
	[3,"Shreya","Singh",14,"MCA"],
	[4,"Shivam","Rao",4,"PHD"]]

with open('mydata.csv', 'w', newline='') as file:
    writer = csv.writer(file, delimiter=',', quoting=csv.QUOTE_ALL, quotechar = '*')
    writer.writerows(data)

Output

*id*,*first_name*,*last_name*,*roll_no*,*course*
*1*,*Vishvajit*,*Rao*,*12*,*BCA*
*2*,*Shivam*,*Kumar*,*13*,*BTech*
*3*,*Shreya*,*Singh*,*14*,*MCA*
*4*,*Shivam*,*Rao*,*4*,*PHD*

Dialects in CSV module

As you can see in the above Python code, we have pass multiple parameters inside csv.reader() function. This practice is good when you working with one or two files but sometimes we have multiple CSV files, then this practice looking weird.

To solve this problem, Python csv Module provide a csv.register_dialect() function which support multiple parameters, that pass into csv.reader() function.

Example: Write CSV file using Dialect

import csv 
data = [["id","first_name","last_name","roll_no","course"],
	[1,"Vishvajit","Rao",12,"BCA"],
	[2,"Shivam","Kumar",13,"BTech"],
	[3,"Shreya","Singh",14,"MCA"],
	[4,"Shivam","Rao",4,"PHD"]]


csv.register_dialect('MyDialect', delimiter=';', quoting=csv.QUOTE_ALL, quotechar='*')
with open('mydata.csv', 'w') as file:
    writer = csv.writer(file, dialect='MyDialect')
    writer.writerows(data)

Output

*id*;*first_name*;*last_name*;*roll_no*;*course*
*1*;*Vishvajit*;*Rao*;*12*;*BCA*
*2*;*Shivam*;*Kumar*;*13*;*BTech*
*3*;*Shreya*;*Singh*;*14*;*MCA*
*4*;*Shivam*;*Rao*;*4*;*PHD*

As you can see in the above example, we have registered a Dialect MyDialect with all the necessary parameters and then pass that dialect to the dialect parameter in csv.writer() function.

Write CSV file using csv.DictWriter()

The object of csv.DictWriter() can is used to write CSV files from a Python dictionary. csv.DictWriter() take two parameters first is filename and the second is fieldsnames.

Example: Write CSV file using csv.DictWriter()

import csv

fieldnames = ['Id', 'Name']
data = [
    {'Id': 1, 'Name': 'Vishvajit'},
    {'Id': 2, 'Name': 'Pankaj'},
]

with open('mydata.csv', 'w',newline='') as file:
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(data)

Output

Id,Name
1,Vishvajit
2,Pankaj

doublequote & escapechar in CSV module

  • doublequote:- This parameter handle how quotechar present in the entry themselve are quoted. When it is True the quoting character is doubled, When it is False, the escapechar is used as prefix to the character. By default value is True.
  • escapechar:- escapechar is a string to escape the delimiter.

Example


import csv 
data = [
    ['ID','First_name','last_name','roll_no','BCA'],
    ['1','"Vishvajit"',12,'BCA'],
    ['2','"Shivam"','Singh',13,'BA'],
    ['3','"Shreya"','Kumari',14,'MCA'],
    ['4','"Vinay"','kumar',15,'BCA']

]

with open('students.csv', 'w') as file:
    writer = csv.writer(file, doublequote=False, escapechar='/')
    writer.writerow(['id','first_name','last_name','roll_no','course'])
    writer.writerows(data)

Output


id,first_name,last_name,roll_no,course
ID,First_name,last_name,roll_no,BCA
1,/"Vishvajit/",12,BCA
2,/"Shivam/",Singh,13,BA
3,/"Shreya/",Kumari,14,MCA
4,/"Vinay/",kumar,15,BCA

Conclusion

So, In this article, we have seen all about the Python CSV Module to write CSV files in Python.csv module in Python is one of the most popular modules to work with CSV file data.

Python CSV module provides lots of functionality to write CSV files, as you can see in the above example. Click here to know all about How to read CSV files using Python.

If you like this article, please share and keep visiting for further Python tutorials.

Read CSV Files in Python:- Click Here

Reference:- Click Here

Previous Article
Next Article

Related Posts