Updated March 27, 2023
Introduction to Python Read CSV File
In this article, we will learn about Python Read CSV File. CSV Module is a built-in module in Python. In order to use it, one needs to just import it in the python environment. Like:
import csv
As the “csv” module is part of the standard library, so one needs not to install. Here csv stands for Comma Separated Values format files (which a tabular form of storing data, easy to read and understand by a human).
A csv file looks like this:
Sr_No, Emp_Name, Emp_City
1, Obama, England
2, Jackson, California
One can notice, commas separate elements in the csv file. There are many functions of the csv module, which helps in reading, writing and with many other functionalities to deal with csv files.
Examples to Implement Python Read CSV File
Let’s explore more about csv through some examples:
Read the CSV File
Example #1
One needs to set the directory where the csv file is kept.
Code:
import os
os.chdir("My Folder/Personnel/EDUCBA/Jan")
Code:
import csv
with open('Emp_Info.csv', 'r') as file:
reader = csv.reader(file)
for each_row in reader:
print(each_row)
Output:
Explanation of the above code: As one can see, “open(‘Emp_Info.csv’)” is opened as the file.”csv.reader()” is used to read the file, which returns an iterable reader object. Here csv.reader() is used to read csv file, however the functionality is customizable.
Example #2
Like, if the file is a semi-colon separated file.
Code:
import csv
with open('Emp_Info.csv', 'r') as file:
reader = csv.reader(file,delimiter = ';')
for each_row in reader:
print(each_row)
Once the reader object is ready, it is looped around to print the content line by line. Delimiter helps to specify the separator of a file.
Try-Finally in csv.reader()
Code:
import csv
file = open('Emp_Info.csv', 'r')
try:
reader = csv.reader(file)
for each_row in reader:
print(each_row)
finally:
file.close()
Output:
Example #3
Now let’s say we have a csv file that looks like this:
Code:
import csv
with open('Emp_Info.csv', 'r') as file:
reader = csv.reader(file)
for each_row in reader:
print(each_row)
Output:
- As one can notice, commas present in “EMP_Address” will make it split into different columns.
- In order to overcome this issue, we can use one parameter inside the csv.reader, i.e. quote char.
Code:
import csv
with open('Emp_Info.csv', 'r') as file:
reader = csv.reader(file,quotechar="'")
for each_row in reader:
print(each_row)
Output:
This quote char helps in the surrounding values of the file with special values/characters. Like here, we quoted all values of the cell with a single inverted comma.
Example #4
Now let say our file looks like this:
One can notice the “whitespaces” before the 2nd and 3rd columns. When this will be read through our code:
Code:
import csv
with open('Emp_Info.csv', 'r') as file:
reader = csv.reader(file)
for each_row in reader:
print(each_row)
Output:
- This kind of result is not expected, and hence we want to skip those whitespaces.
- Hence,the parameter “skipinitialspace” needs to be utilized in csv.reader():
Code:
import csv
with open('Emp_Info.csv', 'r') as file:
reader = csv.reader(file,skipinitialspace=True)
for each_row in reader:
print(each_row)
Output:
Example #5
Now say we have double quotes in our cells.
Code:
import csv
with open('Emp_Info.csv', 'r') as file:
#reader = csv.reader(file,quoting=csv.QUOTE_NONE)
reader = csv.reader(file,doublequote=True)
for each_row in reader:
print(each_row)
Output:
- Here, the consecutive double quote will be converted to a single quote when doublequote = True.
- Hence make doublequote = False.
Code:
import csv
with open('Emp_Info.csv', 'r') as file:
reader = csv.reader(file,doublequote=False)
for each_row in reader:
print(each_row)
Output:
Here, consecutive double quotes will be displayed as it is.
Reading CSV File using csv.DictReader()
Code:
import csv
with open("Emp_Info.csv", 'r') as file:
csv_reader = csv.DictReader(file)
for each_row in csv_reader:
print(dict(each_row))
Output:
- Here csv_reader is csv.DictReader() object. Here csv.DictReader() helps reading the csv file in the form of a dictionary, where the first row of the file becomes “keys” and the rest of all rows become “values”.
- The first row had “Sr_No”,” Emp_Name”, and “Emp_City”, so these became keys, whereas the rest rows become their value.
- Csv.DictReader() in itself returns a dictionary of each row, that when doing dict() explicitly as per your requirement is futile.
Code:
csv.register_dialect(
'mydialect',
delimiter = ';',
skipinitialspace = True,
quotechar = '"',
doublequote = True,
)
Now this defined dialect can be used directly while reading or writing a csv file.
reader = csv.reader(csv_file, dialect='mydialect')
Conclusions
As we saw above, how important is the concept of csv reading in Python? There are various methods and parameters related to it. Every parameter has its significance while dealing with csv reading as well as writing a file. One needs to be familiar with it and practice it to get a good grip over it.
Recommended Articles
This is a guide to Python Read CSV File. Here we discuss an introduction, csv through some examples with proper codes and outputs. You can also go through our other related articles to learn more –