Py学习  »  Python

简单天气信息操作的while循环中的python索引错误

neo-ned • 5 年前 • 1317 次点击  

有人能从下面的索引错误中发现明显的错误吗?我创建了一个简单的操作,它从.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()

我的指数值如下:

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

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

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

这是我的错误: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

如果我运行.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>
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38124
 
1317 次点击  
文章 [ 1 ]  |  最新文章 5 年前