Wednesday, 9 April 2025

GRADE 12: PRACTICAL 8 : CSV FILES

 ''' Write a menu driven program to perform the following

functions on a csv file ‘ Student.csv’ 

i) Accept details of n students

and write into the file. The header will be :

[Student roll, Student Name, Student Marks]

ii)Display the contents of the file

iii)Function to display the average marks of all the

students who have got Distinction(above 75% marks) 

iv)Function to search for a given roll number and

display the details if found, else display an error.

'''

import csv


def menu():

    while True :

        ch=int(input("""MENU :

1.Accept

2.Display

3.Average

4.Search

5.Exit

"""))

        if ch==1:

            accept()

        elif ch==2:

            display()

        elif ch==3:

            average()

        elif ch==4:

            search()

        else:

            break


def accept():

    n=int(input("Enter no of records : "))

    with open("student.csv","a",newline="") as f:

        c=csv.writer(f)

        if f.tell()==0:

            c.writerow(['Student roll', 'Student Name',' Student Marks'])

        for i in range(n):

            roll=input("Enter roll no : ")

            name=input("Enter name : ")

            marks=input("Enter marks : ")

            c.writerow([roll,name,marks])


def display():

    with open("student.csv","r")as f:

        c = csv.reader(f)

        

        for a,b,c in c:

            print(a.ljust(15),b.ljust(15),c.ljust(15))

            

def average():

    with open("student.csv","r") as f:

        c=csv.reader(f)

        header=next(c)

        l=[]

        for i in c:

            mark=int(i[2])

            if mark>=75:

                l.append(mark)

        print(sum(l)/len(l))

                  

def search():

    roll=input("Enter roll number to be searched : ")

    with open("student.csv","r") as f:

        c=csv.reader(f)

        header=next(c)

        for i in c:

            if i[0]==roll:

                print("student found : ",i)

                break

        else:

            print("Student not found ")

    

menu()


No comments:

Post a Comment