Read text file into dictionary removing heading/trailing newlines

夙愿已清 提交于 2019-12-11 15:04:28

问题


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'}]

How do I fix that?


回答1:


Whereever you read using readline(), use readline().strip()




回答2:


[community wiki, because this is really a long comment]

(1) I'd call your function employee_read and not employee_write.

(2) Rather than all that duplication, I might do:

def employee_read(source):
    keys = "First Last Experience ID Gender".split()
    employee_dict = {key: next(source).strip() for key in keys}
    return employee_dict

(3) Your main function could instead be written

def main():
    with open("employees.txt") as fp:
        n = int(next(fp))
        employees = [employee_read(fp) for i in range(n)]
    print employees

which gives

>>> main()
[{'Gender': 'M', 'Last': 'Doe', 'ID': '272838', 'Experience': '33', 'First': 'John'},
{'Gender': 'F', 'Last': 'Johnson', 'ID': '3849383', 'Experience': '38', 'First': 'Mary'}]



回答3:


.strip() without an argument strips all spaces/tabs/newlines




回答4:


Append .rstrip('\n') to your readline calls to sanitize the newline out of the line.



来源:https://stackoverflow.com/questions/15440785/read-text-file-into-dictionary-removing-heading-trailing-newlines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!