How to read a Python CSV file
We will learn how to read a CSV file in Python in this shot. Let’s start by understanding what a CSV file is.
What is a CSV file?
- A CSV file is a comma-separated values file.
- Information is organized in tabular form.
- The delimiter doesn’t need to be a comma
,because there are other delimiters such as tab\t, the colon:, and semi-colon;.
Sample CSV file
EMPLOYEE_ID,FIRST_NAME,LAST_NAME
198,Donald,OConnell
199,Douglas,Grant
200,Jennifer,Whalen
Example 1
main.py
employee.csv
#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)
Explanation
- Line 2: Import the
csvmodule, which is provided by Python. - Line 5: Open the CSV file as
employeeFile. - Line 6: Read the CSV file with the
reader()method, which accepts a file object and delimiter as parameters. - Line 9: Loop through the iterator returned by
csv.reader(). - Line 10: Print each row. It will print each row as a list.
Example 2
In this example, we will try to get the info of the employee with ID 198.
main.py
employee.csv
#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)
Explanation
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.