• Read CSV files without headers using CSV module reader function, and read headers with the DictReader class in Python

How to read CSV files in Python

python has a CSV library, that you need to read and write modules emp.csv file contains comma-separated values as given

1,john,2000,sales
11,Andrew,5000,finance
21,Mark,8000,hr

Read CSV file line by line

First, Import csv module into the code using the import statement

import csv

Next, Open the file using open with the name of the file.

file = open('emp.csv')

If the file is not found, It throws FileNotFoundError: [Errno 2] No such file or directory:. and stack trace is

Traceback (most recent call last):
  File "a:\work\python\csv-read..py", line 2, in <module>
    file = open('emp1.csv')
FileNotFoundError: [Errno 2] No such file or directory: 'emp.csv'

Next, Create a reader using the CSV reader` function, and pass the file variable to it.

reader = csv.reader(file)

Use for in loop to read the line by line, and print the line. Each line is a row in a CSV file with many columns.

for line in reader:
    print(line)

Here is a complete example

import csv
file = open('emp1.csv')
reader = csv.reader(file)
for line in reader:
    print(line)

Output:

['1', 'john', '2000', 'sales']
['11', 'Andrew', '5000', 'finance']
['21', 'Mark', '8000', 'hr']

You can access individual values using line[0] for first value, second value using line[1]

How to read a csv file with a header in Python

Sometimes, CSV file contains headers id, name, salary, and dept as given below The first line contains the header columns.

id,name,salary,dept
1,john,2000,sales
11,Andrew,5000,finance
21,Mark,8000,hr

DictReader class used instead reader function. It pro

import csv
with open("emp.csv") as csvfile:
    reader = csv.DictReader(csvfile)
    columnNames = reader.fieldnames
    print(columnNames)

Output:

['id', 'name', 'salary', 'dept']

To read the csv file with column names using DictReader

  • Create a DictReader class
  • Iterate each row using for in loop
  • print using row[columnname] to get the value
import csv
with open("emp.csv") as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row['id']+" - "+row['name'])

How to write to CSV file in Python

To write to CSV file in Python, Please follow the below steps.

  • Open a file in write mode using open function
with open("emp1.csv","w",newline="") as csvfile:
  • Create a Writer using DictWriter with file and headernames
  • Write header using writeheader(), creates first line of header column names
  • Add data using writeRow function with an object of key and values.

Here is a python write CSV file example


import csv
with open("emp1.csv","w",newline="") as csvfile:
    headernames=["id","name"]
    writer=csv.DictWriter(csvfile,headernames)
    writer.writeheader()
    writer.writerow({'id':'11','name':'aaa'})
    writer.writerow({'id':'21','name':'eee'})
    writer.writerow({'id':'31','name':'ccc'})


emp1.csv file created with below rows

id,name
11,aaa
21,eee
31,ccc