CSV
CSV
import csv
def write():
f=open('books.csv','w')
swriter=csv.writer(f)
swriter.writerow(['Book_Name','Author_Name','Price'])
rec=[]
while True:
Book_Name=input('Enter Book Name: ')
Author_Name=input('Enter Author Name: ')
Price=int(input('Enter Price= '))
data=[Book_Name,Author_Name,Price]
rec.append(data)
choice=input('DO YOU WANT TO ADD MORE DATA(Y/N): ')
if choice in 'nN':
break
swriter.writerows(rec)
print('DATA ADDED SUCCESSFULLY')
f.close
write()
OUTPUT:
#Ques-2
import csv
def StudentWrite():
with open("Student.csv",'w',newline="") as f:
csv_w=csv.writer(f,delimiter=',')
csv_w.writerow(("Roll no","Name", "Percentage"))
rec=[]
while True:
rn=int(input('Roll no:'))
nm=input('Name:')
pr=int(input('Percentage:'))
rec.append([rn,nm,pr])
ch=input('Want to enter more records Y/N=')
if ch.lower()=='n':
break
csv_w.writerows(rec)
def StudentRead():
with open("Student.csv",'r') as f:
csv_read=csv.reader(f,delimiter=',')
for row in csv_read:
for i in range(len(row)):
print(row[i],end='\t')
print()
def StudentSearch():
with open("Student.csv",'r') as f:
flag=0
csv_read =csv.reader(f)
header=next(csv_read)
rnos=input('Enter roll no to be searched:')
for row in csv_read:
if row[0]==rnos:
print('found')
flag=1
print(row)
else:
flag=0
continue
if flag==0:
print('Not found')
def StudentCount():
count=0
with open("Student.csv",'r') as f:
csv_read=csv.reader(f)
header=next(csv_read)
try:
for row in csv_read:
count+=1
except EOFError:
pass
print(count)
while True:
ch=int(input('Enter choice:'))
if ch==1:
StudentWrite()
elif ch==2:
StudentRead()
elif ch==3:
StudentSearch()
elif ch==4:
StudentCount()
elif ch==5:
print('Exiting..')
break
else:
print('Please input valid option')
OUTPUT:
****BASIC CSV FUNCTIONS****
1. Create a csv file
2. Read and display
3. Search a Roll no.
4. Count the no. of records
5. Exit
Enter choice:1
Roll no:1
Name:Ritvik
Percentage:99
Want to enter more records Y/N=Y
Roll no:2
Name:Anand
Percentage:98
Want to enter more records Y/N=Y
Roll no:3
Name:Rahul
Percentage:97
Want to enter more records Y/N=N
Enter choice:2
Roll no Name Percentage
1 Ritvik 99
2 Anand 98
3 Rahul 97
Enter choice:3
Enter roll no to be searched:1
found
['1', 'Ritvik', '99']
Enter choice:4
3
Enter choice:5
Exiting..