如果我只是向您展示我正在使用的文本文件和我拥有的代码,这将更容易理解。这是名为 employees.txt 的文本文件:
7
John
Doe
33
272838
M
Mary
Johnson
38
3849383
.....
现在我有两个功能。他们来了:
def employee_write(file):
employee_dict = {}
employee_dict["First"] = file.readline()
employee_dict["Last"] = file.readline()
employee_dict["Experience"] = file.readline()
employee_dict["ID"] = file.readline()
employee_dict["Gender"] = file.readline()
return employee_dict
def main():
file = open("employees.txt", "r")
n = int(file.readline())
x1 = employee_write(file)
employee_list = []
for i in range(n):
employee_list.append(x1)
x2 = employee_list
print(x2)
不幸的是,当我打印出字典列表时,我在第一个函数中附加到键的值都带有一个换行符,如下所示:
[{'ID': '272838\n', 'Last': 'Doe\n', 'First': 'John\n', 'Experience': '33\n', 'Gender': 'M\n'}, {'ID': '272838\n', 'Last': 'Doe\n', 'First': 'John\n', 'Experience': '33\n', 'Gender': 'M\n'}, {'ID': '272838\n', 'Last': 'Doe\n', 'First': 'John\n', 'Experience': '33\n', 'Gender': 'M\n'}, {'ID': '272838\n', 'Last': 'Doe\n', 'First': 'John\n', 'Experience': '33\n', 'Gender': 'M\n'}, {'ID': '272838\n', 'Last': 'Doe\n', 'First': 'John\n', 'Experience': '33\n', 'Gender': 'M\n'}, {'ID': '272838\n', 'Last': 'Doe\n', 'First': 'John\n', 'Experience': '33\n', 'Gender': 'M\n'}, {'ID': '272838\n', 'Last': 'Doe\n', 'First': 'John\n', 'Experience': '33\n', 'Gender': 'M\n'}]
我该如何解决?