What are CSV file format?
A CSV (Comma Separated Values) file is a simple file format that allows to save a file in a tabular format from a spreadsheet application. Excel spreadsheets and databases are frequently imported and exported as CSV files . This is one of the most common methods for exchanging data between applications and is a popular data format for analytics and data science studies supported by a wide range of applications. Each field of a CSV file has a delimiter (in most cases, a comma) to divide the data into rows and columns. The CSV format must be saved with the .csv extension.
Let us look at how to read and write a csv file using python in this article.
- Reading a CSV file in Python
Here let me take “iris.csv” file. Required Python Library is Pandas and the function is read_csv.
#Import pandas as pd from pandas library.
import pandas as pd
pd.read_csv(“iris.csv”)
iris.head() # for displaying first 5 rows
iris.shape # displays the size of the dataset in rows and columns which is (150,6)
- Writing CSV files in Python.
There are in-built modules available for writing csv files in python and it can be done in 2 ways –
- Using csv.writer class.
- Using csv.DictWriter class.
Using csv.writer class, data is inserted in the csv file. In this class, data is converted into a delimited string using a writer object. csv.writer class provides two methods of writing the csv –
- writerow(): This method writes a single row at a time.
- writerows(): This method is used to write multiple rows at a time.
# Python program to demonstrate writing to CSV.
import csv
# Fields
fields = [‘Name’, ‘Branch’, ‘Year’, ‘CGPA’]
# Data rows of csv file
rows = [ [‘Joey’, ‘COE’, ‘2’, ‘9.0’],
[‘Chandeller’, ‘COE’, ‘2’, ‘9.1’],
[‘Phoebe’, ‘IT’, ‘2’, ‘9.3’],
[‘Monica’, ‘SE’, ‘1’, ‘9.5’],
[‘Ross’, ‘MCE’, ‘3’, ‘7.8’],
[‘Rachel’, ‘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)
# zWriting the data rows
csvwriter.writerows(rows)
Output: once you run the code the .csv file will be saved on your PC.
Using csv.DictWriter class provides two methods for writing to csv.
They are:
- writeheader() method simply writes the first row of your csv using the pre-specified field names.
- writerows() this method simply writes all the rows but in each row, it writes only the values.
# Importing the csv module in python
import csv
# my data rows as dictionary objects
mydict =[{‘branch’: ‘COE’, ‘cgpa’: ‘9.0’, ‘name’: ‘Joey’, ‘year’: ‘2’},
{‘branch’: ‘COE’, ‘cgpa’: ‘9.1’, ‘name’: ‘Chandeller’, ‘year’: ‘2’},
{‘branch’: ‘IT’, ‘cgpa’: ‘9.3’, ‘name’: ‘Phoebe’, ‘year’: ‘2’},
{‘branch’: ‘SE’, ‘cgpa’: ‘9.5’, ‘name’: ‘Monica’, ‘year’: ‘1’},
{‘branch’: ‘MCE’, ‘cgpa’: ‘7.8’, ‘name’: ‘Ross’, ‘year’: ‘3’},
{‘branch’: ‘EP’, ‘cgpa’: ‘9.1’, ‘name’: ‘Rachel’, ‘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)
Output:
These are the methods regarding how to read and write csv files in python. These are commonly used tasks to fetch and save data in an analytics and data science application.