有人能发现任何明显的错误吗?我创建了一个简单的操作,它从一个.txt文件中获取数据并以特定格式打印信息。这并不复杂,但我得到一个索引错误,我不知道为什么索引存在
city_info = open("mean_temp.txt", "a+")
city_info.write("Rio de Janeiro,Brazil,30.0,18.0\n")
city_info.seek(0,0)
headings = city_info.readline().split(",")
print("heading index 0:", headings[0],"\n","heading index 1:",
headings[1],"\n","heading index 2:", headings[2],"\n","heading index 3:",
headings[3])
while city_info:
city_temp = city_info.readline().split(",")
print(headings[0], "of", city_temp[0], "is", city_temp[2], "Celcius")
city_info.close()
我的索引值如下:
这是我当前的输出(看起来是正确的(忽略数字),但我只需要消除索引错误。你知道吗
This is my error: IndexError
Traceback (most recent call last) <ipython-input-5-fb9cc0942cef> in <module>() 20 while city_info: 21 city_temp = city_info.readline().split(",") ---> 22 print(headings[0], "of", city_temp[0], "is", city_temp[2], "Celcius") 23 24 IndexError: list index out of range
If i run the URL for the location the .txt file is stored in i get and i can't find any blank lines:
<p> city,country,month ave: highest high,month ave: lowest low <p>Beijing,China,30.9,-8.4 <p>Cairo,Egypt,34.7,1.2 <p>London,UK,23.5,2.1 <p>Nairobi,Kenya,26.3,10.5 <p>New York City,USA,28.9,-2.8 <p>Sydney,Australia,26.5,8.7 <p>Tokyo,Japan,30.8,0.9 <p> <p>
由于文件成功打开,
city_info
将永远是true
。循环将保持读取直到超过EOF
,因此city_temp
的内容成为空列表。你知道吗我认为循环应该重写为:
相关问题 更多 >
编程相关推荐