簡體   English   中英

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

[英]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()

我不明白為什么會出現錯誤:

列表索引超出范圍

在輸出中。 我試圖將 readline 和 split 分開以確保 while 循環只接收字符串。

當你附加到你的文件時,你最終是這樣的:

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
"

您添加的行附加到最后一行的末尾,而不是新行。 所以你得到一個超出范圍的索引,因為你的文件的最后一行沒有這些索引。

在添加新行之前嘗試附加回車符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM