Python中的split和readline - 列表索引超出范围

时间:2017-09-23 17:40:35

标签: python indexing split readline

!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和split分开,以确保while循环只接收字符串。

1 个答案:

答案 0 :(得分: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
"

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

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