是我的第一篇文章,对不起格式
问题: 输出中有错误,数据输出正确,但循环超出范围,我不知道如何修复它。
代码:
exam_file=open('mean_text.txt', 'a+')
exam_file.write("Rio de Janeiro,Brazil,30.0,18.0\n")
exam_file.seek(0)
headings=exam_file.readline().split(",")
exam_file.seek(0,1)
city_temp=exam_file.readline().split(",")
while city_temp:
print(headings[0].capitalize()+" of "+city_temp[0]+" "+ headings[2]+" is "+city_temp[2]+" Celsius")
city_temp = exam_file.readline().split(",")
exam_file.close()
输出:
City of Beijing month ave: highest high is 30.9 Celsius
Traceback (most recent call last):
City of Cairo month ave: highest high is 34.7 Celsius
City of London month ave: highest high is 23.5 Celsius
File "./Module4task.py", line 11, in <module>
City of Nairobi month ave: highest high is 26.3 Celsius
City of New York City month ave: highest high is 28.9 Celsius
print(headings[0].capitalize()+" of "+city_temp[0]+" "+ headings[2]+" is "+city_temp[2]+" Celsius")
City of Sydney month ave: highest high is 26.5 Celsius
IndexError: list index out of range
City of Tokyo month ave: highest high is 30.8 Celsius
City of Rio de Janeiro month ave: highest high is 30.0 Celsius
.txt文件的内容:
city,country,month ave: highest high,month ave: lowest low
Beijing,China,30.9,-8.4
Cairo,Egypt,34.7,1.2
London,UK,23.5,2.1
Nairobi,Kenya,26.3,10.5
New York City,USA,28.9,-2.8
Sydney,Australia,26.5,8.7
Tokyo,Japan,30.8,0.9
期待:
City of Beijing month ave: highest high is 30.9 Celsius
City of Cairo month ave: highest high is 34.7 Celsius
City of London month ave: highest high is 23.5 Celsius
City of Nairobi month ave: highest high is 26.3 Celsius
City of New York City month ave: highest high is 28.9 Celsius
City of Sydney month ave: highest high is 26.5 Celsius
City of Tokyo month ave: highest high is 30.8 Celsius
City of Rio De Janeiro month ave: highest high is 30.0 Celsius
我的任务:
添加Rio的天气
以附加加模式打开文件(&#39; a +&#39;)
为里约热内卢和巴西里约热内卢写一个新的线路,30.0,18.0 \ n&#34; 抓住列标题
使用while循环从文件中读取剩余的行
提示&amp;提示:
•打印标题以确定用于最终输出的索引(标题[0],[1],[2]中的内容..?)
•city_temp数据遵循标题的顺序(city_temp [0]由标题[0]描述)
•输出应如下所示:&#34;月份平均值:最高值&#34;对于北京是30.9摄氏度
•将city_temp转换为带有.split的列表(&#39;,&#39;)
答案 0 :(得分:0)
尝试更改while循环,以便有一个端点
就像尝试在到达文件末尾后添加break语句一样(使用len查找它的长度)
或者您可以在while语句中添加一个条件来检查文件是否在最后