我使用以下Python代码从文本文件中读取最后第三行。它有超过40000行:
my_file1.close()
with open (L[i],"r") as my_file3:
for line in my_file3:
if line.strip():
count+=1
count=count-5
print (count)
with open (L[i],"r") as my_file3:
lines=my_file3.readlines()
temp=lines[count].split()
cpu[i]=temp[4]
pht[i]=temp[1]闲人告诉我"IndexError:列表索引超出了范围“。有人能帮我个忙吗?
发布于 2014-02-09 16:35:44
您无法解释使用strip()的原因。要获得第5行,请使用:
lines = open("in.txt").readlines()
line = lines[-5]发布于 2014-02-09 17:19:58
首先,从文件中获取第五行非空行的正确方法是:
lines = [l for l in my_file where l.strip()]
temp = lines[-5].split()(您可以使用不那么简单的代码来消除内存开销,但就目前而言,这是切线。)
如果这不能消除您的错误,问题在于行中没有足够的空格分隔标记,或者在cpu或pht中没有i元素。
https://stackoverflow.com/questions/21660842
复制相似问题