Python文件写入异常:输入三名员工名仅保留最后一个的解决方法
问题修复:正确保存多个员工姓名
原代码的问题根源
在addInfo函数中存在两个关键错误:
- 输入姓名时,每次都将新输入的值覆盖到变量
data中,导致前两次输入的姓名丢失,最终data仅保留最后一个姓名。 - 写入文件的循环重复写入的是最后一次的
data值,因此文件中只会重复出现同一个姓名。
修改方案
- 使用列表存储所有输入的姓名,避免单变量覆盖问题。
- 写入文件时遍历列表,逐个写入每个姓名。
- 改用
with语句处理文件操作,无需手动调用close(),既保证资源安全释放,又简化代码。 - 移除冗余的
createFile函数,因为Python的open()函数在w/a模式下,若文件不存在会自动创建。
修改后的完整代码
def addInfo(): # 初始化列表存储所有员工姓名 employees = [] for _ in range(3): name = input("Type the name of the employee: ") employees.append(name) # with语句自动管理文件,无需手动close with open("namesEmployees.txt", "w") as employee_file: for name in employees: employee_file.write(f"{name}\n") print("The names have been added") def displayInfo(): with open("namesEmployees.txt", "r") as employee_file: print(employee_file.read()) # 执行功能 addInfo() displayInfo()
可选优化:追加模式
如果需要保留文件原有内容,将新姓名追加到末尾,只需把open的模式从w改为a:
with open("namesEmployees.txt", "a") as employee_file:
内容的提问来源于stack exchange,提问作者Andrea
相关产品推荐
相关产品推荐

