Advertisement
gruntfutuk

employee

Oct 30th, 2022
997
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.29 KB | None | 1 0
  1. from typing import Dict
  2. import csv
  3. from pathlib import Path
  4.  
  5. from employee_class import Employee
  6. from password_func import generate_password
  7.  
  8.  
  9. def save_employees(filename: Path, employees: Dict[str, Employee]):
  10.     """ save dictionary of Employee records to a CSV file """
  11.     if employees:  # check there's data to save, assume the data is valid
  12.         with filename.open('w') as file:  # open file (new or overwrite)
  13.             writer = csv.writer(file)  # writing in csv format
  14.             for employee in employees.values():  # retrieve each Employee record
  15.                 writer.writerow(employee.row())  # convert record to list of fields for CSV and write
  16.  
  17.  
  18. def read_employees(filename: Path):
  19.     """ read Employee records from CSV into dictionary of Employee records"""
  20.     employees: Dict[str, Employee] = {}  # start with empty dictionary
  21.     if filename.is_file():  # make sure there is a file, lets assume we can read it
  22.         with filename.open() as file:
  23.             reader = csv.reader(file)
  24.             for idx, row in enumerate(reader):  # need a row number for error reporting
  25.                 try:  # attempt to convert row from csv data into an Employee record
  26.                     new_employee = Employee(*row)
  27.                 except TypeError:  # probably too few/many fields on the row
  28.                     print(f'Bad Record - row {idx}: {row}')
  29.                 except ValueError as err:  # probably failed check there is a number for salary
  30.                     print(f'Bad Record - row {idx}: {row}')
  31.                     print(err)
  32.                 else:  # add new Employee record to dictionary if not duplicate name
  33.                     if not add_employee(new_employee, employees):
  34.                         print(f'Duplicate Name - row {idx}: {row}')
  35.  
  36.     return employees  # dictionary of Employee records
  37.  
  38.  
  39. def add_employee(new_employee: Employee, employees: Dict[str, Employee]):
  40.     key = new_employee.key()  # generate unique key for potential new employee
  41.     if key in employees:  # check key is unique, if not retain False
  42.         return False
  43.     employees[key] = new_employee  # otherwise add employee to dictionary of Employee records
  44.     return True  # and return True to indicate new employee was added succesfully
  45.  
  46.  
  47. def report(employees: Dict[str, Employee], report_header: str = "\n\nEmployees:\n", report_footer: str = ""):
  48.     """ print details of all Employee records in dictionary """
  49.     print(report_header)
  50.     for employee in employees.values():
  51.         print()
  52.         print(employee)
  53.     print(report_footer)
  54.  
  55.  
  56. filename = Path('employees.csv')
  57.  
  58. employees = read_employees(filename)  # see if we have employee data filed already
  59. if employees:
  60.     report(employees, "\nEmployee details read from file:\n")
  61.  
  62. # lets try to add some additional employees
  63. new_emps = (Employee('Fred', "Bloggs", "William", "S5", 23_000, "Junior Chef"),
  64.             Employee('Barry', "Smoth", "", "S6", 18_000, "Washer"),
  65.             Employee('Alpha', "Beta", "Charlie", "S2", 43_000, "CFO", generate_password()),
  66.             )
  67.  
  68. for employee in new_emps:
  69.     if add_employee(employee, employees):
  70.         print('\nAdded employee, ', employee)
  71.     else:
  72.         print('\nEmployee already on file - details not changed')
  73.         print(employee)
  74.  
  75. save_employees(filename, employees)
  76. report(employees, '\n\nSaved to file Employee Details:\n')
  77.  
Tags: class employee
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement