Python索引错误在while循环中用于简单的天气信息操作



任何人都可以通过我得到的以下索引错误发现任何明显的内容吗?我创建了一个简单的操作,它从.txt文件中获取数据并以特定格式打印信息。这并不复杂,但我遇到索引错误,我不确定为什么,因为索引存在;

city_info = open("mean_temp.txt", "a+")
city_info.write("Rio de Janeiro,Brazil,30.0,18.0n")
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()

我的指数值如下;

  1. 标题索引 0:城市
  2. 标题索引1:国家
  3. 标题指数2:月平均:最高高
  4. 标题索引3:月平均:最低低点

这是我当前的输出(看起来正确(忽略数字(,但我只需要摆脱索引错误。

  1. 北京市是 30.9 摄氏度
  2. 开罗市是 34.7 摄氏度
  3. 伦敦市是 23.5 摄氏度
  4. 内罗毕市 是 26.3 摄氏度
  5. 纽约市 是 28.9 摄氏度
  6. 悉尼市 是 26.5 摄氏度
  7. 东京市是30.8摄氏度
  8. 里约热内卢市是 30.0 摄氏度

这是我的错误:索引错误

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

如果我运行存储.txt文件的位置的 URL,我会得到并且找不到任何空白行:

<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的内容变为空列表。

我认为循环应该重写为:

for line in city_info:
city_temp = line.split(",")
print(headings[0], "of", city_temp[0], "is", city_temp[2], "Celcius")

最新更新