将文本文件读入字典去除标题/尾随换行符 [英] Read text file into dictionary removing heading/trailing newlines
本文介绍了将文本文件读入字典去除标题/尾随换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我只是向你显示我正在使用的文本文件和我的代码,这将会更容易理解。这是文本文件,名为employees.txt:
This will be much easier to understand if I just show you the text file I'm working with and the code I have. Here's the text file, called employees.txt:
7
John
Doe
33
272838
M
Mary
Johnson
38
3849383
.....
现在我有两个功能。这里是:
Now I have two functions. Here they are:
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)
不幸的是,当我打印出字典列表时,我附加到第一个函数中的键的值全部出现在附带的换行符,如下所示:
Unfortunately, when I print out the list of dictionaries, the values that I attached to the keys in the first function all come out with a newline character attached, like this:
[{'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'}]
如何解决?
推荐答案
使用 readline()
阅读时,请使用 readline()。 strip()
这篇关于将文本文件读入字典去除标题/尾随换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文