Python
In this tutorial we will learn to write data in CSV file in Python.
In the previous tutorial we covered how to read data from CSV file. Feel free to check that out.
csv
To save data in CSV file we have to take help of the csv module. So, go ahead and import the module by writing the following code.
import csv
To write data in CSV file we will first create a new file using the open() method.
open()
Let's name our file as sample.csv.
sample.csv
To write data we will use the DictWriter class of the csv module. We will pass the file object that holds the reference to the newly created CSV file and the variable that holds the fields name.
DictWriter
To write the fields name we will use the writeheader() method.
writeheader()
To write the data rows we will use the writerow() method.
writerow()
For this tutorial we will write the following data in the sample.csv file.
playerid,score 1,10 2,9 3,12
Where, playerid,score in the 1st row are the fields. The remaining 3 rows are the data.
playerid,score
In the following Python program we are writing the sample data in sample.csv file.
The data is in dictionary form inside a list.
# import module import csv try: # create file fobj = open('score.csv', 'w') # fields fields = ['playerid', 'score'] # data to save in csv file data = [ {'playerid': 1, 'score': 10}, {'playerid': 2, 'score': 9}, {'playerid': 3, 'score': 12} ] # writer writer = csv.DictWriter(fobj, fields) # write the header writer.writeheader() # write the data for row in data: writer.writerow(row) except: print("An error occurred while writing the file.") finally: fobj.close()
On executing the above code we will get the sample.csv file containing the following data.