在python中将txt文件读入字典

时间:2016-08-05 08:44:37

标签: python

我在尝试将此 txt 文件读入python中的字典时遇到问题。怎么办?

colModel

1 个答案:

答案 0 :(得分:0)

您可以使用以下行打开文件:

with open('<filename>') as f:

这会将名为f的变量设置为文件。 你可以尝试使用拆分功能

with open('<filename>') as f:
    dict = {}
    for line in f:
        part_one, part_two = line.split(" ")
        dict[part_one] = part_two

    print(dict)

我相信如果您的文件中的每条记录都在新行IE上,这应该有效:

NAMES MARKS
Lux 95
Veron 70
Lesley 88
Sticks 80
Tipsy 40
Joe 62
Goms 18
Wistly 35
Villa 11
Dentist 72
Onty 50