''' Write a menu-driven program to perform the following
functions on a csv file ‘Cricket.csv’
i) Accept details of n players and write into the file.
The header will be: [Player ID, Player Name, Team, Runs Scored]
ii) Display the id, names and runs of all players who have scored
century. Also display the average of such players.
iii) Search for a player by name and display their details
if found, else show "Player not found."
iv) Update the runs scored by a player (given their Player ID)
If found, ask for new runs and update the file.
'''
import csv
def menu():
while True :
ch=int(input("""MENU :
1.Accept
2.Display
3.Search
4.Update
5.Exit
"""))
if ch==1:
accept()
elif ch==2:
display()
elif ch==3:
search()
elif ch==4:
update()
else:
break
def accept():
n=int(input("Enter no of records : "))
with open("cricket.csv","a",newline="") as f:
writer=csv.writer(f)
if f.tell()==0:
writer.writerow(['Player ID', 'Player Name',' Team', 'Runs Scored'])
for i in range(n):
pid = input("Enter Player ID: ")
name = input("Enter Player Name: ")
team = input("Enter Team Name: ")
runs = int(input("Enter Runs Scored: "))
writer.writerow([pid, name, team, runs])
def display():
with open("cricket.csv","r")as f:
reader = csv.reader(f)
title=next(reader)
high=[]
print('ID'.ljust(15),'NAME'.ljust(15),'RUNS'.ljust(15))
for a,b,c,d in reader:
if int(d)>=100:
high.append(int(d))
print(a.ljust(15),b.ljust(15),d.ljust(15))
if len(high)==0:
print( 'No such records')
else:
print('Average of the top batsmen : ', sum(high)/len(high))
def search():
name=input("Enter player name to be searched : ")
with open("cricket.csv","r") as f:
reader=csv.reader(f)
header=next(reader)
for i in reader:
if i[1]==name:
print("Player found : ",i)
break
else:
print("Player not found ")
def update():
with open('Cricket.csv','r') as f:
c=csv.reader(f)
l=list(c)
pid=input("enter player id to be updated")
for i in l[1:]:
if pid==i[0]:
i[3]=int(input("Enter new no of runs"))
break
else:
print("player not found")
with open('Cricket.csv','w',newline='') as f:
c=csv.writer(f)
c.writerows(l)
menu()
No comments:
Post a Comment