Welcome folks today in this post we will be talking about how to write csv files using csvwriter class and dictwriter class
. This will be a full project for beginners in python 3. All the source code of examples are shown below.
Installation
In order to get started you should have installed python
on your system and also we must need a module called as csv
for interacting with csv files in python. You can install that module using pip command as follows
pip install csv
Methods Used
Now to Write CSV Files in Python we will be using two classes namely called csvwriter
and dictwriter
in csv module.
First we will discuss csvwriter
class so make a app.py
file and write code in that
In this csvwriter
class we have two methods
writerow
This is a method used to write a single row to a csv file at a time
writerows
This method can be used to write multiple rows to a csv file at a time
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# Python program to demonstrate # writing to CSV 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) |
Now we will talk about the second class DictWriter
class to write csv files
Inside this class we have two methods
writeheader
This method is used to write the header of the csv files namely the columns
writerows
This method writes all the rows at once except it doesn’t write keys only values
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
# 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) |