社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

neo-ned • 4 年前 • 622 次点击  

有人能从下面的索引错误中发现明显的错误吗?我创建了一个简单的操作,它从.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
 
622 次点击  
文章 [ 1 ]  |  最新文章 4 年前
sal
Reply   •   1 楼
sal    5 年前

因为文件打开成功, 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")