We will learn how to read a CSV file in Python in this shot. Let’s start by understanding what a CSV file is.
,
because there are other delimiters such as tab \t
, the colon :
, and semi-colon ;
.EMPLOYEE_ID,FIRST_NAME,LAST_NAME
198,Donald,OConnell
199,Douglas,Grant
200,Jennifer,Whalen
#importing csv module import csv #open csv file and read with open('employee.csv') as employeeFile: read_csv = csv.reader(employeeFile, delimiter = ',') #print each row for row in read_csv: print(row)
csv
module, which is provided by Python.employeeFile
.reader()
method, which accepts a file object and delimiter as parameters.csv.reader()
.In this example, we will try to get the info of the employee with ID 198
.
#importing csv module import csv #open and read csv file with open('employee.csv') as employeeFile: read_csv = csv.reader(employeeFile, delimiter = ',') #traverse every row in csv for row in read_csv: #check for id if(row[0] == '198'): #print employee print(row)
Example 2 is the same as example 1, except that in line 11, we use the if
statement to check if the present employee ID matches the given ID. If they match, we print the employee info.
RELATED TAGS
CONTRIBUTOR
View all Courses