CBSE Class XII: Python Data File Handling | CSV Files

CSV Files to Store and Read Employee Data

Question:3
Python program to create a CSV file named “employee.csv”, to store employee details like empno,Name and salary of employees.
Sol:

#writing records in csv file
import csv
f=open('employee.csv','w',newline='')
empwriter=csv.writer(f,delimiter=',')
empwriter.writerow(['Empno','Name','Salary']) # write header row
emprec= [ 
      ['1001', 'Amit', '45000'], 
     ['1002', 'Sagar', '19800'], 
     ['1003', 'Aditi', '29855'], 
     ['1004', 'Sansar', '86790'], 
     ['1005', 'Pramod', '88000'], 
       ] 
empwriter.writerows(emprec)
f.close()

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

Question:4
Python program read the contents of CSV file named “employee.csv”, and display Empno,Name and Salary of employees.
Sol:

# method 1
import csv
with open("employee.csv","r",newline='') as fh:
    empreader=csv.reader(fh)
    for rec in empreader:
        print(rec)
#method 2
with open("employee.csv","r",newline='') as fh:
    empreader=csv.reader(fh)
    for rec in empreader:
        for i in rec:
            print(i,end=' ')
        print('\n')

Output:

[‘Empno’, ‘Name’, ‘Salary’]
[‘1001’, ‘Amit’, ‘45000’]
[‘1002’, ‘Sagar’, ‘19800’]
[‘1003’, ‘Aditi’, ‘29855’]
[‘1004’, ‘Sansar’, ‘86790’]
[‘1005’, ‘Pramod’, ‘88000’]


Empno Name Salary

1001 Amit 45000

1002 Sagar 19800

1003 Aditi 29855

1004 Sansar 86790

1005 Pramod 88000