【发布时间】:2020-06-08 10:16:02
【问题描述】:
name,score #an example
a,1,
s,2,
d,3,
f,4,
g,5,
h,6,
j,7,
k,8,
l,9,
q,10,
这是我的文件。我想把它写成字典 (a:1,s:2...)
number_of_lines = len(open("scores.txt").readlines( ))
d = {}
with open("scores.txt") as f:
for line in range(number_of_lines-1): #-1 removes the last line which is only \n
(key, value) = line.split(",")
d[key] = value
print(d)
我不断收到错误 AttributeError: 'int' object has no attribute 'split' 不知道为什么。
你能调试一下吗?
提前致谢,
【问题讨论】:
-
range(number_of_lines-1)将为您提供从 0 到 number_of_lines -1 的整数,因此 line 将是一个整数,并且每个循环都会增加。所以,0, 1, 2, 3等等,所以你不能拆分一个 int。你的意思是(key, value) = f.readline().split(",")但我不明白你为什么关心文件的长度 -
@ChrisDoyle 感谢您的回复。然后长度是一个问题,因为那时我得到的错误只有 2,因为文件末尾还有另一行只有 \n
-
@Daniel 这与你在循环中的逻辑有关。您可以安全地执行
if len(line.strip()) == 0: continue,假设您实际上将行本身放在变量line中。请参阅下面的代码,第三个示例。应该更详细地解释这一点。
标签: python file dictionary