Previous Index Next

Solved Examples - CSV File Handling

Question 1

A CSV file student.csv has following contents:
Rno,Name,Score,Class
101,Alex,80,12
102,Monica,84,12
103,Ajay,72,12
104,Irfan,82,11
Write a function count_rec() that count and display number of records where score is more than 80.

Solution

import csv

def count_rec():
    file = open("student.csv","r")
    count = 0
    creader = csv.reader(file)
    next(creader)
    for row in creader:
        if int(row[2])>80:
            count += 1
    print("Number of records are",count)
    file.close()

count_rec()

Output

Number of records are 2

Question 2

A CSV file result.csv has following contents:
Rno,Name,P,C,M
101,Alex,78,55,89
102,Monica,65,67,71
103,Ajay,77,87,79
104,Irfan,90,89,92

Write a function make_copy() that creates a new CSV file copy.csv containing all records of result.csv after adding the marks of PCM. The file copy.csv contents should be like:

Rno,Name,Total
101,Alex,222
102,Monica,203
103,Ajay,243
104,Irfan,271

Solution

import csv

def make_copy():
    infile = open("result.csv","r")
    outfile = open("copy.csv","w",newline="")
    creader = csv.reader(infile)
    cwriter = csv.writer(outfile)
    next(creader)
    cwriter.writerow(['Rno','Name','Total'])
    for row in creader:
        sum = int(row[2])+int(row[3])+int(row[4])
        cwriter.writerow([row[0],row[1],sum])
    infile.close()
    outfile.close()

make_copy()

Question 3

Write a program to create a CSV File 'Student.csv' (content shown below). Content of CSV file is input by user.

Rollno,Name,Class
1,Sakham,XII
2,Nisha,XII
3,Irfan,XII
4,Vaani,XII
5,Jasvinder,XII

Solution

import csv
file = open('student.csv', 'w', newline='')
mywriter = csv.writer(file)
data = [ ]
header = ['Rollno', 'Name', 'Class']
data.append(header)
for i in range(5):
    rollno = int(input("Enter Roll Number : "))
    name = input("Enter Name : ")
    Class = input("Enter Class : ")
    rec = [rollno,name,Class]
    data.append(rec)
    mywriter.writerow(data)
file.close()

Output

Enter Roll Number : 1
Enter Name : Sakham
Enter Class : XII
Enter Roll Number : 2
Enter Name : Nisha
Enter Class : XII
Enter Roll Number : 3
Enter Name : Irfan
Enter Class : XII
Enter Roll Number : 4
Enter Name : Vaani
Enter Class : XII
Enter Roll Number : 5
Enter Name : Jasvinder
Enter Class : XII


Previous Index Next