Write employee records to a CSV file and display employees earning above 50000
Expt. No.18
Page No.36
CSV: employees above 50000
Aim
To write a Python program that writes employee records to a CSV file with writerows(), then reads the file and displays employees with salary above 50000.
Concepts used
Algorithm
- Store the header and the employee rows in a list of lists.
- Write them all with writerows().
- Read the file with csv.reader(); skip the header row.
- Convert the salary to int and display the rows with salary above 50000.
Program
# Write employees to a CSV file and show salaries above 50000 import csv rows = [["EmpNo", "Name", "Salary"], [101, "Ravi", 45000], [102, "Meena", 52000], [103, "Arjun", 38000], [104, "Sara", 61000], [105, "Vikram", 50000]] with open("employees.csv", "w", newline="") as f: w = csv.writer(f) w.writerows(rows) print("Employees earning above 50000:")with open("employees.csv", "r") as f: r = csv.reader(f) for row in r: if row[0] != "EmpNo" and int(row[2]) > 50000: print(row[0], row[1], row[2])
A marked line continues the line above it. In your file, write it on the same line.
Output
$ python csv_employees.py
Employees earning above 50000:
102 Meena 52000
104 Sara 61000
✓ Printed by running this program, not typed by hand.
Contents of employees.csv
employees.csvafter the run
EmpNo,Name,Salary 101,Ravi,45000 102,Meena,52000 103,Arjun,38000 104,Sara,61000 105,Vikram,50000
Result
Six rows were written with one call to writerows(). Meena (52000) and Sara (61000) were displayed; Vikram's 50000 is not above 50000.
Viva voce: what the examiner may ask
01Why is int(row[2]) needed?
csv.reader() returns every value as a string; "61000" > 50000 would raise a TypeError.
02How is the header row skipped?
By checking row[0] != "EmpNo", since the header's first value is the column name.
03What separates the values in a CSV file?
A comma, by default.
Variations for the lab test
- Display the total salary of all employees.
- Add a new employee to the file using "a" mode.
- Write the employees above 50000 to a second CSV file.
! Common mistake Comparing
row[2] > "50000" compares strings letter by letter, so "6000" would wrongly count as greater.