Python Tutorial | Python Data File Handling 17

Question:3
Python program to create a CSV file, to store Name, Branch, Year and CGPA of student.
Sol:

#csv1
#to create a csv file

# importing the csv module 
import csv 

# field names 
fields = ['Name', 'Branch', 'Year', 'CGPA'] 

# data rows of csv file 
rows = [ ['Nikhil', 'CSE', '2', '9.0'], 
		['Sanchit', 'CSE', '2', '9.1'], 
		['Aditya', 'IT', '2', '9.3'], 
		['Sagar', 'SE', '1', '9.5'], 
		['Prateek', 'MCE', '3', '7.8'], 
		['Sahil', 'EC', '2', '9.1']] 

# name of csv file 
filename = "university_records.csv"

# writing to csv file 
with open(filename, 'w') as csvfile: 
	# creating a csv writer object 
	csvwriter = csv.writer(csvfile) 
	
	# writing the fields 
	csvwriter.writerow(fields) 
	
	# writing the data rows 
	csvwriter.writerows(rows)
	

After the execution of the above file, a csv file named “university_records.csv” gets created. It is an excel file.

 

Question:4
Python program read the contents of CSV file named “student.csv”, and display Name, Branch, Year and CGPA of students.
Sol:

# importing csv module 
import csv 

# csv file name 
#filename = "aapl.csv"
filename = "university_records.csv"

# initializing the titles and rows list 
fields = [] 
rows = [] 

# reading csv file 
with open(filename, 'r') as csvfile: 
	# creating a csv reader object 
	csvreader = csv.reader(csvfile) 
	
	# extracting field names through first row 
	fields = next(csvreader) 

	# extracting each data row one by one 
	for row in csvreader: 
		rows.append(row) 

	# get total number of rows 
	print("Total no. of rows: %d"%(csvreader.line_num)) 

# printing the field names 
print('Field names are:' + ', '.join(field for field in fields)) 

# printing first 5 rows 
print('\nFirst 15 rows are:\n') 
for row in rows[:15]:
    # parsing each column of a row
    for col in row:
        print(col,end=' ') 
    print('\n') 

Output:

Total no. of rows: 14
Field names are:Name, Branch, Year, CGPA

First 15 rows are:



Nikhil CSE 2 9.0 



Sanchit CSE 2 9.1 



Aditya IT 2 9.3 



Sagar SE 1 9.5 



Prateek MCE 3 7.8 



Sahil EC 2 9.1 



>>>