Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python

How to read a Python CSV file

Gutha Vamsi Krishna

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 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)
An example of reading a CSV file

Explanation

  • Line 2: Import the csv module, 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 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)
An example of reading a CSV file

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.

RELATED TAGS

communitycreator
python
RELATED COURSES

View all Courses

Keep Exploring