CSV Files to Store and Read Student Data
Question:1
Python program to create a CSV file named “student.csv”, to store Roll,Name and Per of students.
Sol:
#writing records in csv file import csv f=open('student.csv','w',newline='') stdwriter=csv.writer(f,delimiter=',') stdwriter.writerow(['Rollno','Name','Marks']) # write header row stdrec= [ ['101', 'Nikhil', '99'], ['102', 'Sanchit', '98'], ['103', 'Aditya', '98'], ['104', 'Sagar', '87'], ['105', 'Prateek', '88'], ] stdwriter.writerows(stdrec) f.close()
After the execution of the above file, a csv file named “student.csv” gets created. It is an excel file.
Question:2
Python program read the contents of CSV file named “student.csv”, and display Roll,Name and Per of students.
Sol:
# method 1 import csv with open("student.csv","r",newline='') as fh: sreader=csv.reader(fh) for rec in sreader: print(rec) #method 2 with open("student.csv","r",newline='') as fh: sreader=csv.reader(fh) for rec in sreader: for i in rec: print(i,end=' ') print('\n')
Output:
[‘Rollno’, ‘Name’, ‘Marks’]
[‘101’, ‘Nikhil’, ’99’]
[‘102’, ‘Sanchit’, ’98’]
[‘103’, ‘Aditya’, ’98’]
[‘104’, ‘Sagar’, ’87’]
[‘105’, ‘Prateek’, ’88’]
Rollno Name Marks
101 Nikhil 99
102 Sanchit 98
103 Aditya 98
104 Sagar 87
105 Prateek 88