1 0
Read Time:4 Minute, 9 Second

Complete study notes & tutorial for reading and writing csv files in python programming

CLICK HERE TO WATCH EXPLANATION ON YOUTUBE

CSV – comma separated files

  • A Comma Separated Values (CSV) file contains data in form of rows & columns like MS Excel
  • These files are often used for exchanging data between different applications.
  • We can open csv file in notepad or ms excel.
  • There are multiple operations that we can do in csv like reading and writing data.
  • Download this exp.csv file for working with the codes given below.

Reading data from csv

  • Display all rows and columns of CSV
  • Accessing each row of csv file one by one, is also called traversing through csv.
  • for reading data we will use reader()
import csv
l = r'C:\Users\gaurav garg\Desktop\exp.csv'
with open(l,'r') as cf:
    cw = csv.reader(cf)
    for i in cw:
        print(i)
cf.close()

OUTPUT : All the data of rows and columns will be displayed like the given below output.

[‘4’, ‘Raj’, ‘delhi’, ‘Accountant’]
[‘2’, ‘Gaur’, ‘delhi’, ‘Engineer’]
[‘3’, ‘Amita’, ‘delhi’, ‘Cook’]
[‘5’, ‘Ganguly’, ‘Kolkata’, ‘Cricket’]

  • Display particular columns
  • We have a file exp.csv that has data in four columns like roll , name , city , profession
  • Column indexes of roll is 0 , name is 1 , city is 2 , profession is 3
  • Display data only of name and city
  • name and city is given in columns index 1 and 2
import csv
l = r'C:\Users\gaurav garg\Desktop\exp.csv'
with open(l,'r') as cf:
    cw = csv.reader(cf)
    for i in cw:
        print(i[1],"--",i[2])
cf.close()

OUTPUT : All the rows will be printed, but data of column name and city will be printed.

See also  split() function Important programs in file handling in python

Raj — delhi
Gaur — delhi
Amita — delhi
Ganguly — Kolkata

  • Display particular rows
  • Display all data of roll no 3
  • Column, roll has index 0
import csv
l = r'C:\Users\gaurav garg\Desktop\exp.csv'
with open(l,'r') as cf:
    cw = csv.reader(cf)
    for i in cw:
        if i[0] == '3':                # i[0] 0 is column index
            print(i)
cf.close()

OUTPUT : All the data of roll 3 wil be printed. we have used conditional statement inside for loop for getting the data of roll 3.

[‘3’, ‘Amita’, ‘delhi’, ‘Cook’]

  • Display data of all students that live in delhi
import csv
l = r'C:\Users\gaurav garg\Desktop\exp.csv'
with open(l,'r') as cf:
    cw = csv.reader(cf)
    for i in cw:
        if i[2] == 'delhi':
            print(i)
cf.close()

OUTPUT : All the rows having city delhi will be printed.

See also  working with functions important programs part 1

[‘4’, ‘Raj’, ‘delhi’, ‘Accountant’]
[‘2’, ‘Gaur’, ‘delhi’, ‘Engineer’]
[‘3’, ‘Amita’, ‘delhi’, ‘Cook’]

Writing data in csv

  • For writing data in csv we will use functions writer() and writerow()
  • we can do it in two mode write mode ‘w’ or append mode ‘a’
  • write mode – previous data will be erased and new data will be written
  • append mode – new data will be written just after the previous data
  • we will work with exp.csv file
  • Writing data using ‘w
import csv
row =  [4,'Raj','delhi','Accountant']
l = r'C:\Users\gaurav garg\Desktop\exp.csv'
with open(l,'w') as cf:
    cw = csv.writer(cf)
    cw.writerow(row)
cf.close()

OUTPUT : The new row will be written in our csv file, and any previous data will be removed. visit the location of csv file in your computer and open the file to see the changes.

  • If we open our csv file in notepad, how the data will look is show below
  • This is the data we just wrote in our exp.csv in the above program

4,Raj,delhi,Accountant

  • Writing data using ‘a
import csv
row =  [2,'Gaur','delhi','Engineer']
l = r'C:\Users\gaurav garg\Desktop\exp.csv'
with open(l,'a',newline='\n') as cf:
    cw = csv.writer(cf)
    cw.writerow(row)
cf.close()
  • Write multiple rows
  • If you want to add all new rows after the old data, open file in ‘w’
  • If you want, old to exist with new rows, then open file in ‘a’
  • In the given below program, we are opening in append ‘a’ mode, so new rows will be added after previous data.
import csv
l = r'C:\Users\gaurav garg\Desktop\exp.csv'
nr = int(input("How Many Rows : "))                  #2
with open(l,'a',newline='\n') as cf:
    for i in range(2):
        r = input("Roll : ")
        n = input("Name : ")
        c = input("City : ")
        d = input("Profession : ")
        row =  [r,n,c,d]
        cw = csv.writer(cf)
        cw.writerow(row)
cf.close()

EXPLANATION : In this program, we will enter how many rows we want to fill in variable nr, so according to this range python interpreter will ask us details of rows, we can easily fill those.

See also  File Handling in Python CBSE Class 12

OUTPUT : After executing the script we can enter how many rows we want to fill, and then we can fill the details. To see the change open the exp.csv file in your computer.

4,Raj,delhi,Accountant
2,Gaur,delhi,Engineer
3,Amita,delhi,Cook
5,Ganguly,Kolkata,Cricket

Happy
Happy
%
Sad
Sad
%
Excited
Excited
%
Sleepy
Sleepy
%
Angry
Angry
%
Surprise
Surprise
%