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 moduleimport csv#open csv file and readwith open('employee.csv') as employeeFile:read_csv = csv.reader(employeeFile, delimiter = ',')#print each rowfor 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 moduleimport csv#open and read csv filewith open('employee.csv') as employeeFile:read_csv = csv.reader(employeeFile, delimiter = ',')#traverse every row in csvfor row in read_csv:#check for idif(row[0] == '198'):#print employeeprint(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.