In this tutorial, we are going to see how to read CSV file in Python.

How to read CSV file in Python:

We have a simple CSV file with first_name, last_name and etc. Now we are going to read this CSV file in Python.

Sample comma-separated file.

data.csv
first_name,last_name,company_name,address,city,county
James,Butt,Benton, John B Jr,6649 N Blue Gum St,New Orleans
Josephine,Darakjy,Chanay, Jeffrey A Esq,4 B Blue Ridge Blvd,Brighton
Art,Venere,Chemel, James L Cpa,8 W Cerritos Ave #54,Bridgeport
Lenna,Paprocki,Feltz Printing Service,639 Main St,Anchorage,Anchorage
Donette,Foller,Printing Dimensions,34 Center St,Hamilton,Butler

Creating a python file to read CSC file.

parse_csv.py
import csv

with open('data.csv','r') as data_file:
    csv_reader = csv.reader(data_file)
    next(csv_reader) #skipping first line in the file
    for line in csv_reader:
        print(line)

Output:

['James', 'Butt', 'Benton', ' John B Jr', '6649 N Blue Gum St', 'New Orleans']
['Josephine', 'Darakjy', 'Chanay', ' Jeffrey A Esq', '4 B Blue Ridge Blvd', 'Brighton']
['Art', 'Venere', 'Chemel', ' James L Cpa', '8 W Cerritos Ave #54', 'Bridgeport']
['Lenna', 'Paprocki', 'Feltz Printing Service', '639 Main St', 'Anchorage', 'Anchorage']
['Donette', 'Foller', 'Printing Dimensions', '34 Center St', 'Hamilton', 'Butler']

Read a specific column in CSV:

As CSV file column-based file, we can get even a particular column data in the file. Here I am going to read the first column, i.e. last_name.

parse_csv.py
import csv

with open('data.csv','r') as data_file:
    csv_reader = csv.reader(data_file)
    next(csv_reader)
    for line in csv_reader:
        print(line[1]) # Reading first column (last_name)

Output:

Butt
Darakjy
Venere
Paprocki
Foller

Happy Learning 🙂