Read specific columns from CSV file in python

Write python program to read specific columns in CSV file with Practical Example.

Program Description :

This program reads specific columns of given CSV file and print the contents of columns.

Program Logic:

  • Include csv module using import statement
  • Open csv file say ’emp.csv’ and store it in file object say ‘f’
  • Create csv reader object ‘ereader’ using DictReader method of csv module
  • Use DictReader method to read all the contents of csv file and pass file object ‘f’ as an argument to DictReader method
  • Tranverse through the ereader object using for loop
  • Write the name of column that you want to display on console using print function
  • Print the content of selected column on console using print statement

Below is implementation code/Source code

import csv
with open("emp.csv",newline='') as f:
    ereader = csv.DictReader(f)
    print("Display only specific columns")
    print("EmpNo Salary")
    print("===============")
    for row in ereader:
        print(row['Empno'],row['Salary'])

Output:

EmpNo Salary

1001 56000
1002 45000
1003 25000

Below is snapshot of executable code with output

<