Python中的拆分和读取行-列表索引超出范围

Python中的拆分和读取行-列表索引超出范围,python,indexing,split,readline,Python,Indexing,Split,Readline,我不明白为什么会出现错误: 列表索引超出范围 在输出中。我已尝试将读线和拆分分开,以确保while循环只接收字符串。在附加到文件时,结果如下: !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 Jane

我不明白为什么会出现错误:

列表索引超出范围


在输出中。我已尝试将读线和拆分分开,以确保while循环只接收字符串。

在附加到文件时,结果如下:

!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()
您要添加的行追加到最后一行的末尾,而不是新行。因此,您会得到一个超出范围的索引,因为在文件的最后一行没有这些索引


尝试在添加新行之前添加回车。

您能否将错误回溯发布到您的问题已被标记为低质量,我以审阅者的身份写信给您。1如果您可以显示输入文件mean_temp.txt的一些内容,这将有助于任何想要回答您问题的人。2使用apple和orange等名称会使代码更难阅读。例如,对于苹果,您可以使用标题_项。我同意@KalyanReddy。这是不正确的。下载的文件已被换行符终止。实际问题是由一个输入错误引起的,它在写入文件的字符串中添加了一个字符。这将创建一个额外的行,当程序需要四个元素时,它将拆分为一个只有一个元素的列表。
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
"