• 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 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 file not found, It throws FileNotFoundError: [Errno 2] No such file or directory:. and stacktrace 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 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 csv file with header in Python

Sometimes, CSV file contains headers id,name,salary,dept as given below 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 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