简体   繁体   中英

split and readline in Python - list index out of range

!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()

I don't understand why there is an error:

list index out of range

in the output. I have tried to separate the readline and split for ensuring the while loop only receive the string.

When you're appending to your file, you end up like this:

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
"

The line you're adding is appending to the end of the last line and not on a new line. So you get an out of range index because you don't have those indices on the last line of your file.

Trying appending a carriage return before adding the new line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM