Python - Read CSV Columns Into List

In this tutorial, you will learn how to read CSV columns into a list in Python. I am giving the following examples:

  1. Read CSV Columns into list and print on the screen.
  2. Read and Print specific columns from the CSV using csv.reader method.
  3. Read CSV via csv.DictReader method and Print specific columns.

For the below examples, I am using the country.csv file, having the following data:

COUNTRY_ID,COUNTRY_NAME,REGION_ID
AR,Argentina,2
AU,Australia,3
BE,Belgium,1
BR,Brazil,2
CA,Canada,2
CH,Switzerland,1
CN,China,3

1. Read CSV Columns into List and Print on The Screen

In the following Python program, it will read the CSV file using the csv.reader method of CSV module and will print the lines.

import csv

with open("country.csv", "r") as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    for lines in csv_reader:
      print(lines)

Output:

['COUNTRY_ID', 'COUNTRY_NAME', 'REGION_ID']
['AR', 'Argentina', '2']
['AU', 'Australia', '3']
['BE', 'Belgium', '1']
['BR', 'Brazil', '2']
['CA', 'Canada', '2']
['CH', 'Switzerland', '1']
['CN', 'China', '3']

Note: To skip the first line (header row), you can use next(csv_reader) command before the FOR LOOP.

2. Read and Print Specific Columns from The CSV Using csv.reader Method

In the following example, it will print the column COUNTRY_NAME, by specifying the column number as 1 (lines[1]). The CSV file is containing three columns, and the column number starts with 0 when we read CSV using csv.reader method.

import csv

with open("country.csv", "r") as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    for lines in csv_reader:
      print(lines[1])

Output:

COUNTRY_NAME
Argentina
Australia
Belgium
Brazil
Canada
Switzerland
China

3. Read CSV via csv.DictReader Method and Print Specific Columns

In the following example, it will read the CSV into a list using csv.DictReader method and will print the columns using column names (COUNTRY_ID, COUNTRY_NAME) available in the header.

import csv

with open("country.csv", "r") as csv_file:
    csv_reader = csv.DictReader(csv_file, delimiter=',')
    for lines in csv_reader:
      print(lines['COUNTRY_ID'], lines['COUNTRY_NAME'])

Output:

AR Argentina
AU Australia
BE Belgium
BR Brazil
CA Canada
CH Switzerland
CN China

See also:

Vinish Kapoor
Vinish Kapoor

Vinish Kapoor is a seasoned software development professional and a fervent enthusiast of artificial intelligence (AI). His impressive career spans over 25+ years, marked by a relentless pursuit of innovation and excellence in the field of information technology. As an Oracle ACE, Vinish has distinguished himself as a leading expert in Oracle technologies, a title awarded to individuals who have demonstrated their deep commitment, leadership, and expertise in the Oracle community.

guest

18 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments