【发布时间】:2018-07-24 08:15:41
【问题描述】:
是我的第一篇文章,对不起格式
问题: 我的输出有错误,数据输出是正确的,但是循环超出范围,我不知道如何修复它。
代码:
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
我的任务:
添加里约天气
以追加模式('a+')打开文件
为 Rio de Janeiro 写一个新行 "Rio de Janeiro,Brazil,30.0,18.0\n" 抓住列标题
- 使用 .seek() 将指针移动到文件的开头
- 将第一行文本读入一个名为:标题的变量中
- 使用 .split(',') 将标题转换为列表,在每个逗号上拆分
使用 while 循环从文件中读取剩余的行
- 将剩余的行分配给 city_temp 变量
- 对循环中的每个 .readline() 使用 .split(',') 将 city_temp 转换为列表
- 打印每个城市和最高月平均气温
- 关闭 mean_temps
提示和提示:
• 打印标题以确定用于最终输出的索引(标题[0]、[1]、[2]..中的内容是什么?)
• city_temp 数据遵循标题的顺序(city_temp[0] 由标题[0] 描述)
• 输出应如下所示:北京的“month ave:highest high”为 30.9 摄氏度
• 使用 .split(',') 将 city_temp 转换为列表
【问题讨论】:
-
您可以先将 while 循环更改为 for 循环,这是迭代文件中行的惯用方式:
for city_temp in exam_file: city_temp = city_temp.split(','); .....docs.python.org/3/tutorial/… -
有些东西真的很奇怪,因为错误消息与输出混合的方式。你是如何运行脚本的?
-
其中一个要求是我必须使用while循环。我在 PyCharm 中运行脚本
-
您的输出与您的脚本不兼容:文本与您打印的不同。请使用您正在运行的确切代码更新您的帖子。至于您的问题,我的猜测是您的文件末尾有一个空行。在这种情况下,
exam_file.readline()将给出\n,它在拆分时给出['\n'],就 while 循环而言,它仍然是 True。 -
如果是这种情况,您可以使用
while len(city_temp) == len(headings):修复(或多或少)它。
标签: python python-3.x loops while-loop