In our Python tutorial, you have learned how to reading CSV file in Python. In this tutorial, you will learn how to write a CSV File in Python.
CSV (comma-separated values) is popular file type used to store and read data. So here in this tutorial, we will use build csv
module to create and write data to csv file.
So let’s proceed with coding.
Steps to write a CSV file
First we will import built-in CSV
module from Python.
import csv
then we will open the file in w
writing mode using open()
function to write into file.
file = open('path/csv_file', 'w')
then we will create a CSV writer object by calling the writer()
function of the csv
module with file object.
writer = csv.writer(file)
then we will write data to the CSV file by calling writerow()
or writerows()
method writer object.
if write single row then we can use writerow()
method.
writer.writerows(columnValues)
if want to write multiple rows then we need to use writerows()
method.
writer.writerows(columnValues)
Finally, close the opened file by calling close()
method.
file.close()
Writing a single row to CSV files
Here is the complete code to create a CSV file and write single rows data.
# write.py import csv columnName = ['name', 'age', 'country'] columnValues = ['Any', 44, 'Germany'] with open('emp.csv', 'w', encoding='UTF8', newline='') as file: writer = csv.writer(file) # write column names writer.writerow(columnName) # write rows values writer.writerow(columnValues)
Writing multiple rows to CSV files
Here is the complete code to create a CSV file and write multiple rows data.
# write.py import csv columnName = ['name', 'age', 'country'] columnValues = [ ['Smith', 30, 'Australia'], ['William', 40, 'Newyork'], ['Andre', 60, 'Germany'], ['Roger', 55, 'Paris'], ['Donal', 33, 'Sydney'] ] with open('employee.csv', 'w', encoding='UTF8', newline='') as file: writer = csv.writer(file) # write column names writer.writerow(columnName) # write rows values writer.writerows(columnValues)