为何程序生成的员工薪资汇总报告数值全为0?
问题:员工薪资汇总数值全部为0的排查与修复
我正在完成一项课程作业程序,已接近完成,但在第96行及后续代码中,尝试生成员工信息汇总报告时,所有汇总数值均被设为0,且无回溯错误。以下是程序代码:
from Data import Employee import queue import csv #Initialize Queues input_queue = queue.Queue() payStubs_queue = queue.Queue() fields = ['ID', 'Name', 'Title', 'Hours Worked', 'Hourly Wage', 'Federal Tax Rate'] rows = [['1234', 'Franklin', 'Engineer', '2', '9.0', '.20'], ['5467', 'Raberto', 'Developer', '2', '9.1', '.20'], ['2345', 'Caity', 'FrontEnd', '2', '9.3', '.20'], ['1235', 'Patrick', 'FrontEnd', '1', '9.5', '.20'], ['3465', 'Prateek', 'Engineer', '3', '7.8', '.20'], ['4567', 'Alberto', 'Engineer', '2', '9.1', '.20'], ['5678', 'Orin', 'Engineer', '2', '9.0', '.20'], ['1678', 'Eric', 'Developer', '2', '9.1', '.20'], ['7565', 'Jose', 'FrontEnd', '2', '9.3', '.20'], ['5677', 'Alberto', 'FrontEnd', '1', '9.5', '.20'], ['7325', 'Alfred', 'Engineer', '3', '7.8', '.20'], ['9043', 'Albert', 'Engineer', '2', '9.1', '.20'], ['3065', 'Sarah', 'FrontEnd', '1', '9.5', '.20'], ['9042', 'John', 'Engineer', '3', '7.8', '.20'], ['2346', 'Tyler', 'Engineer', '2', '9.1', '.20']] filename = "EmployeeInfo.csv" '''Writing to the File.''' try: with open(filename, 'w', newline='') as csv_file: csv_writer = csv.writer(csv_file) csv_writer.writerow(fields) csv_writer.writerows(rows) except IOError: print("This file does not exist.") except Exception as err: print(f"Unexpected error opening {filename} is",repr(err)) except OSError: print(f"OS error occurred trying to open {filename}") '''Reading the File.''' try: '''with open('EmployeeInfo.csv') as csv_file: csv_reader = csv.reader(csv_file) for line in csv_file: emp_id, first_name, job_title, hours_worked, hourly_wage, federal_tax_rate = (field.strip() for field in line.split(","))''' with open('EmployeeInfo.csv') as csv_file: cvsRead = csv.reader(csv_file) next(csv_file, None) for line in cvsRead: emp_id, first_name, job_title, hours_worked, hourly_wage, federal_tax_rate = (field.strip() for field in line) employee = Employee(emp_id, first_name, job_title, float(hours_worked), float(hourly_wage), float(federal_tax_rate)) input_queue.put(employee) except IOError: print("This file does not exist.") except Exception as err: print(f"Unexpected error opening {filename} is",repr(err)) except OSError: print(f"OS error occurred trying to open {filename}") '''Process data from the input queue and enqueue pay stubs into the payStubs queue.''' while not input_queue.empty(): employee = input_queue.get() gross_pay = employee.calculate_gross_pay() federal_tax = employee.calculate_federal_tax() state_tax = 0.1 * gross_pay social_security_tax = 0.05 * gross_pay medicare_tax = 0.02 * gross_pay net_pay = gross_pay - (federal_tax + state_tax + social_security_tax + medicare_tax) pay_stub = (employee.emp_id, f'{employee.first_name}', gross_pay, federal_tax, state_tax, social_security_tax, medicare_tax, net_pay) payStubs_queue.put(pay_stub) '''Saves pay stub into text file.''' try: with open('Covington.txt', 'w') as output_file: while not payStubs_queue.empty(): pay_stub = payStubs_queue.get() output_file.write(','.join(map(str, pay_stub)) + '\n') except IOError: print("This file does not exist.") except Exception as err: print(f"Unexpected error opening {filename} is",repr(err)) except OSError: print(f"OS error occurred trying to open {filename}") '''Generates a summary report.''' total_gross_pay = 0 total_federal_tax = 0 total_state_tax = 0 total_social_security_tax = 0 total_medicare_tax = 0 try: with open('summary.txt', 'w') as summary_file: while not payStubs_queue.empty(): pay_stub = payStubs_queue.get() total_gross_pay += pay_stub[2] total_federal_tax += pay_stub[3] total_state_tax += pay_stub[4] total_social_security_tax += pay_stub[5] total_medicare_tax += pay_stub[6] summary_file.write(f'Employee ID: {pay_stub[0]}, Employee Name: {pay_stub[1]}, Net Pay: {pay_stub[7]}\n') except IOError: print("This file does not exist.") except Exception as err: print(f"Unexpected error opening {filename} is",repr(err)) except OSError: print(f"OS error occurred trying to open {filename}") try: with open('summary.txt', 'w') as summary_file: summary_file.write(f'Total Gross Pay for All Employees: {total_gross_pay}\n') summary_file.write(f'Total Federal Taxes Withheld for All Employees: {total_federal_tax}\n') summary_file.write(f'Total State Taxes Withheld for All Employees: {total_state_tax}\n') summary_file.write(f'Total Social Security Withheld for All Employees: {total_social_security_tax}\n') summary_file.write(f'Total Medicare Amount Withheld for All Employees: {total_medicare_tax}\n') except IOError: print("This file does not exist.") except Exception as err: print(f"Unexpected error opening {filename} is",repr(err)) except OSError: print(f"OS error occurred trying to open {filename}") #Prints summary to the screen print(f'Total Gross Pay for All Employees: {total_gross_pay}\n') print(f'Total Federal Taxes Withheld for All Employees: {total_federal_tax}\n') print(f'Total State Taxes Withheld for All Employees: {total_state_tax}\n') print(f'Total Social Security Withheld for All Employees: {total_social_security_tax}\n') print(f'Total Medicare Amount Withheld for All Employees: {total_medicare_tax}\n')
问题原因
核心问题是**payStubs_queue队列在生成Covington.txt时已被完全取空**:
在"Saves pay stub into text file"代码块中,while not payStubs_queue.empty()循环会取出队列中所有的薪资存根并写入文件,执行完毕后队列变为空。后续生成汇总报告时,再次遍历空队列,没有任何数据可以累加,导致所有total_*变量保持初始值0。
另外,原代码中两次用'w'模式打开summary.txt,第二次写入会直接覆盖第一次的员工明细内容,这也是需要修复的问题。
修复方案
方案一:用列表存储薪资数据(推荐)
在生成薪资存根时,同时存入一个列表,后续所有操作都基于这个列表,避免队列被取空的问题:
- 修改数据处理部分,新增列表存储薪资存根:
# 新增列表存储所有薪资存根 pay_stubs_list = [] '''Process data from the input queue and enqueue pay stubs into the payStubs queue.''' while not input_queue.empty(): employee = input_queue.get() gross_pay = employee.calculate_gross_pay() federal_tax = employee.calculate_federal_tax() state_tax = 0.1 * gross_pay social_security_tax = 0.05 * gross_pay medicare_tax = 0.02 * gross_pay net_pay = gross_pay - (federal_tax + state_tax + social_security_tax + medicare_tax) pay_stub = (employee.emp_id, f'{employee.first_name}', gross_pay, federal_tax, state_tax, social_security_tax, medicare_tax, net_pay) payStubs_queue.put(pay_stub) pay_stubs_list.append(pay_stub) # 将存根加入列表
- 修改保存薪资文件的代码,遍历列表而非队列:
'''Saves pay stub into text file.''' try: with open('Covington.txt', 'w') as output_file: for pay_stub in pay_stubs_list: output_file.write(','.join(map(str, pay_stub)) + '\n') except IOError: print("This file does not exist.") except Exception as err: print(f"Unexpected error opening {filename} is",repr(err)) except OSError: print(f"OS error occurred trying to open {filename}")
- 修改汇总报告代码,用列表计算并合并写入逻辑(避免覆盖):
'''Generates a summary report.''' total_gross_pay = 0 total_federal_tax = 0 total_state_tax = 0 total_social_security_tax = 0 total_medicare_tax = 0 try: with open('summary.txt', 'w') as summary_file: # 写入员工明细并计算汇总 for pay_stub in pay_stubs_list: total_gross_pay += pay_stub[2] total_federal_tax += pay_stub[3] total_state_tax += pay_stub[4] total_social_security_tax += pay_stub[5] total_medicare_tax += pay_stub[6] summary_file.write(f'Employee ID: {pay_stub[0]}, Employee Name: {pay_stub[1]}, Net Pay: {pay_stub[7]}\n') # 写入汇总数据 summary_file.write('\n') summary_file.write(f'Total Gross Pay for All Employees: {total_gross_pay}\n') summary_file.write(f'Total Federal Taxes Withheld for All Employees: {total_federal_tax}\n') summary_file.write(f'Total State Taxes Withheld for All Employees: {total_state_tax}\n') summary_file.write(f'Total Social Security Withheld for All Employees: {total_social_security_tax}\n') summary_file.write(f'Total Medicare Amount Withheld for All Employees: {total_medicare_tax}\n') except IOError: print("This file does not exist.") except Exception as err: print(f"Unexpected error opening {filename} is",repr(err)) except OSError: print(f"OS error occurred trying to open {filename}")
方案二:调整执行顺序
如果必须使用队列,可以先执行汇总计算,再生成Covington.txt文件,确保队列数据先用于汇总再被取出写入文件。
内容的提问来源于stack exchange,提问作者fskiddles
相关产品推荐
相关产品推荐

