Python - Read CSV Columns Into List

  • Python
  • 2 mins read

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:

This Post Has 18 Comments

  1. nimmmmmm

    how can we change column values from string to float in csv file in python?

    1. Vinish Kapoor

      The above example is to read values from a CSV file and after reading a value into list you can convert it using the float() function.

      If I am not getting it right, then describe you question in more detail on our forum orclqa.com

  2. sunardo

    How to parse subcolumn in nested column?

    Example:
    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'], lines['CAPITAL'])

        AR Argentina Buenos Aires

    Country has data Country_ID and Country_Name.
    I want to remove first subcolumn Country_ID.

    How to achieve that?

    1. Vinish Kapoor

      I think you have to use the functions to pick the substring of a string. For example, if you know that the country id is of 2 character length, then you can use the slicing method as following:

      with open("country.csv", "r") as csv_file:
        csv_reader = csv.DictReader(csv_file, delimiter=’,’)
        for lines in csv_reader:
         c = lines[‘COUNTRY’]
         c = [3:]
      

      Now the first 3 characters (country id and a space) will be removed from lines['COUNTRY'].

    2. sunardo

      Is there any method?
      because I don't know exactly the characters length of the first subcolumn.
      It's only has delimiter (for example white space or tab)

    3. Vinish Kapoor

      You can use split() function.

      Example:

      country = c.split(" ", 1)[1]
      

      it will split on a space and will limit to one split.

    4. sunardo

      Great.
      can you help me how to trim and save it to output file?

    5. Vinish Kapoor

      You need to follow the below steps to write to a file using Python:

      file1 = open("myfile.txt","w") 
      Line = ["This is Delhi \n","This is Paris \n","This is London \n"]  
        
      file1.write("Hello \n") 
      file1.writelines(Line) 
      file1.close()
      
    6. sunardo

      Ok. thank you very much

  3. nitish

    how to get it in same line?

    1. Vinish Kapoor

      Put end = " " in the end of print command. Following are the examples:

      print(lines[1], end =" ")
      

      or

      print(lines['COUNTRY_ID'], lines['COUNTRY_NAME'], end = " ")
      

      For Python version 2.x, add comma in end:

      print(lines[1]),
      
  4. wm7354

    How to select a specific column value and use it in a iteration?

    1. Vinish Kapoor

      Check the below example:

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

           
      The variable v_column_value will be assigned a country name value if the variable n is 0.

      And after assigning, it will set n to 1, so that in next iteration it will not change.

      So now you have the value of a column in a variable, you can use it in whole iteration.

    2. sarasa

        if n = 0:
           ^
      SyntaxError: invalid syntax

      still have the same problem, when I wrote my own code and when I pasted yours. do you have any idea why is that?

    3. Vinish Kapoor

      oh it was mistake in the code, it should be if n== 0: instead of if n=0:.

  5. shivani

    how to sum the paticular column in csv file

  6. victoria

    How to know how many lines on the csv file and how to print only for certain line, lets say print line 3
    Thank you

  7. Adrian

    How would I add a column or multiple column to separate lists using this format

Comments are closed.