Python write to CSV file
In this post, you will learn how to write data to a CSV file using the Python programming language.
In the wake of dealing with a dataset and doing all the preprocessing, we require to save the preprocessed information into some data format like in csv , excel or others. CSV (Comma-separated-values) is widely used for data exchange in data-based applications. In web applications, we generally store the data in an array, dataframe, lists, tuples, dictionaries, etc. There may be a need for clients to export this data to a CSV file. The data in CSV is stored as sequences of records. Like in other programming languages, we can also write data to a CSV file in Python.
Python csv module
Python provides an in-built module csv to work with CSV files. This module provides the following classes to write data to a CSV file.
- csv.writer class
- csv.DictWriter class
Python write to CSV using csv.writer class
The csv.writer() method is used to insert data into a CSV file. This method in the CSV module returns a writer object that is responsible for converting data into a delimited string and storing it in a file object.
Syntax of csv.writer()csv.writer(csvfile)
Here, csvfile is a file object.
There are two methods available of the class csv.writer() for writing to CSV.
- writerow(): This method is used to write a single row at a time.
- writerows(): This method is used to write multiple rows at a time.
In the given example, first we have opened the CSV file for writing by using the open() function. Next, we created a CSV writer object by calling the writer() function of the CSV module. Then, we write data to the CSV file by calling the writerow() or writerows() method of the CSV writer object. At last, we have closed the file object.
# 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)
Python write to CSV using csv.DictWriter class
The csv.DictWriter() class is also used to write data to CSV. It creates an object that operates like a regular writer but maps dictionaries into CSV rows. The fieldnames parameter is a sequence of keys that identify the order in which values in the dictionary passed to the writerow() method are written to the CSV file.
Syntax of csv.DictWriter() class
csv.DictWriter(file, fieldnames)
Here, the file is the CSV file where we want to write data. The fieldnames is a sequence of keys that identify the order in which values in the dictionary passed to the writerow() method are written to the file.
The following example demonstrates the uses of csv.DictWriter() class.
import csv
f = open("fruits.csv", "w")
writer = csv.DictWriter(
f, fieldnames=["fruit", "count"])
writer.writeheader()
f.close()
Related Articles
Python Pandas CSV to Dataframe
Python Converting a CSV File to a MySQL Table
Python Convert XML to CSV
Convert JSON to CSV using Python
Convert list to dictionary Python
Python dict inside list
Pandas string to datetime
Convert Excel to CSV Python Pandas
Python Pandas Dataframe to CSV
Python compare two lists
Remove element from list Python
Python iterate list with index
Python program to sum all the numbers in a list
Python print without newline
Python iterate list with index
Python add list to list
Python convert xml to dict
Python dict inside list
Python convert dict to xml
Python weather api
Python raise keyword