CSV files are one of the most efficient tools to store structured, tabular data. Sometimes, we might need to append data to the CSV file from a python dictionary. In this article, we will discuss how we can append the values in a dictionary to a CSV file in python.
Append Dictionary to CSV File Using csv.writer()
You can append a dictionary to CSV file using CSV.writer()
method and CSV.writerow()
method. For this, we will first open the CSV file in append mode using the open()
function. The open()
function takes the filename as its first input argument and the literal “a
” as its second input argument to denote that the file is opened in the append mode.
After opening the file, we will create a CSV writer object using the CSV.writer()
function. The CSV.writer()
function takes the file object containing the CSV file as its input argument and returns a writer object.
After creating the writer object, we will append the dictionary to the CSV file using the w
riterow() method. The writerow()
method, when invoked on a writer object, takes the values in the dictionary as its input argument and appends it to the CSV file.
After execution of the writerow()
method, you must close the CSV file using the close()
method. Otherwise, the changes won’t be saved in the CSV file. The source code for this approach to append a dictionary to a CSV file is given below.
import csv
myFile = open('Demo.csv', 'r+')
print("The content of the csv file before appending is:")
print(myFile.read())
myDict = {'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
print("The dictionary is:")
print(myDict)
writer = csv.writer(myFile)
writer.writerow(myDict.values())
myFile.close()
myFile = open('Demo.csv', 'r')
print("The content of the csv file after appending is:")
print(myFile.read())
Output:
The content of the csv file before appending is:
Roll,Name,Language
1,Aditya,Python
2,Sam, Java
3, Chris, C++
The dictionary is:
{'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
The content of the csv file after appending is:
Roll,Name,Language
1,Aditya,Python
2,Sam, Java
3, Chris, C++
4,Joel,Golang
Append Dictionary to CSV File using csv.DictWriter()
Instead of using the csv.writer()
method, we can use the csv.DictWriter()
function along with the csv.writerow()
method to append a python dictionary to csv file. The approach is almost similar to the approach using the csv.writer()
method with the following differences.
- Instead of the
csv.writer()
method, we will use thecsv.DictWriter()
method. TheDictWriter()
method takes the file object containing the csv file as its input argument and returns a DictWriter object. - When the
writerow()
method is executed on the DictWriter object, it takes a dictionary as the input argument instead of the values in the dictionary.
The python code to append a dictionary to a csv file using csv.DictWriter()
is as follows.
import csv
myFile = open('Demo.csv', 'r+')
print("The content of the csv file before appending is:")
print(myFile.read())
myDict = {'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
print("The dictionary is:")
print(myDict)
writer = csv.DictWriter(myFile, fieldnames=list(myDict.keys()))
writer.writerow(myDict)
myFile.close()
myFile = open('Demo.csv', 'r')
print("The content of the csv file after appending is:")
print(myFile.read())
Output:
The content of the csv file before appending is:
Roll,Name,Language
1,Aditya,Python
2,Sam, Java
3, Chris, C++
The dictionary is:
{'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
The content of the csv file after appending is:
Roll,Name,Language
1,Aditya,Python
2,Sam, Java
3, Chris, C++
4,Joel,Golang
Conclusion
In this article, we have discussed two ways to append a dictionary to csv file in python. In these approaches, the dictionary will be appended irrespective of whether it has same number of items as compared to the columns in the csv file or it has the same keys as compared to the column names in the csv file. Thus it advised to make sure that the dictionary should have the same number of keys as compared to the columns in the csv file. Also You should make sure that the order of columns of the csv file should be same as the order of the keys present in the dictionary. Otherwise, the data appended to the csv file will become inconsistent and will lead to errors.
I hope you enjoyed reading this article.To know more about dictionaries in python, you can read this article on dictionary comprehension in python. You might also write this article on list comprehension in python.
Stay tuned for more informative articles.
Happy Learning!
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.