我最近问了一个关于将值列表从 txt 文件转换为字典列表的问题。你可以从这里的链接看到它:See my question here
P883, Michael Smith, 1991
L672, Jane Collins, 1992
(added)
(empty line here)
L322, Randy Green, 1992
H732, Justin Wood, 1995(/added)
^key ^name ^year of birth
===============
this question has been answered and i used the following code (accepted answer) which works perfectly:
def load(filename): students = {}infile = open(filename) for line in infile: line = line.strip() parts = [p.strip() for p in line.split(",")] students[parts[0]] = (parts[1], parts[2]) return students
然而,当 txt 文件中的值中有一个行空间时。(请参阅添加的部分)它不再工作并给出一个错误,指出列表索引超出范围。
请您参考如下方法:
检查 for 循环中的空行并跳过它们:
for line in infile:
line = line.strip()
if not line:
continue
parts = [p.strip() for p in line.split(",")]
students[parts[0]] = (parts[1], parts[2])
