2017-09-23 47 views
-2
!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/worl 
d_temp_mean.csv -o mean_temp.txt 
weather = open('mean_temp.txt','a+') 
weather.write('Rio de Janeiro,Brazil,30.0,18.0\n"') 
weather.seek(0) 
headings = weather.readline() 
apple = headings.split(',') 
city_temp = weather.readline() 
orange = city_temp.split(',') 
while city_temp: 
    orange = city_temp.split(',') 
    print (apple[2] + ' of ' + orange[1] + ' is ' + orange[2] + ' Celsius') 
    city_temp = weather.readline() 
weather.close() 

我不明白为什么有一个错误:分裂和readline - 列表索引超出范围

list index out of range

输出

。我试图分开readline和split,以确保while循环只接收字符串。

+2

你也可以发布错误追溯 –

+2

你的问题已被标记为低质量,我写信给你作为审稿人。 (1)如果你能显示输入文件的一些内容,“mean_temp.txt”,那么任何想回答你的问题的人都会很有帮助。 (2)使用像“apple”和“orange”这样的名字会让你的代码难以阅读。例如,对于'apple',你可以使用'heading_items'来代替。 (3)我同意@KalyanReddy。 –

回答

0

当你追加到您的文件,你最终是这样的:

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.9Rio de Janeiro,Brazil,30.0,18.0 
" 

要添加的行追加到最后一行的末尾,而不是在新的一行。所以你会得到一个超出范围的索引,因为你的文件的最后一行没有这些索引。

试图在添加新行之前附加回车符。

+1

这是不正确的。下载的文件已被换行符终止。实际的问题是由一个拼写错误造成的,该错误在写入该文件的字符串中添加了一个''',这会创建一个额外的行,当该程序期待四个时,该行会分成只有一个元素的列表。 – ekhumoro