Python Tutorial | Python Data File Handling 18

Question:5
Python program to create a CSV file named “employee.csv”, to store employee details like empcode, name, deptname and salary.
Sol:

#csv file example
#to create a csv file
# importing the csv module 
import csv 
# field names 
fields = ['EmpCode', 'Name', 'Department', 'Salary'] 
# data rows of csv file 
rows = [ ['1001', 'Amit', 'Sales', '230000'], 
	 ['1002', 'Sonu', 'Finance', '340000'],
	 ['1003', 'Aditya', 'Purchase', '56000'], 
	 ['1004', 'Sanjay', 'Sales', '55000'], 
	 ['1005', 'Prashant', 'Finance', '65000'], 
       ] 
# name of csv file 
filename = "employee.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 “employee.csv” gets created. It is an excel file.

 

Question:6
Python program read the contents of CSV file named “employee.csv”, and display empcode, name, deptname and salary of employees.
Sol:

# importing csv module 
import csv 
# csv file name 
filename = "employee.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: 12
Field names are:EmpCode, Name, Department, Salary

First 15 rows are:



1001 Amit Sales 230000 



1002 Sonu Finance 340000 



1003 Aditya Purchase 56000 



1004 Sanjay Sales 55000 



1005 Prashant Finance 65000 



>>> 

Visitor Counter

0051051