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

2024-10-01 07:42:48 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能发现任何明显的错误吗?我创建了一个简单的操作,它从一个.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塞尔西乌斯
  5. 纽约市为28.9塞尔西乌斯
  6. 悉尼市为26.5塞尔西乌斯
  7. 东京城是30.8塞勒斯
  8. 里约热内卢市为30.0塞尔西乌斯

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>

Tags: oftheinfotxtcityreadlineindexis
1条回答
网友
1楼 · 发布于 2024-10-01 07:42:48

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

相关问题 更多 >