Reputation: 11
I'm working on an a assignment for an edx course and I'm having an "index out of range" error in my code when it runs a while loop, even though it gives the right output eventually.
This is my code:
# [] create The Weather
# [] copy and paste in edX assignment page
!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/world_temp_mean.csv -o mean_temp.txt
mean_temp = open('mean_temp.txt', 'a+')
mean_temp.write("Rio de Janeiro,Brazil,30.0,18.0\n")
mean_temp.seek(0)
headings = mean_temp.readline().split(',')
city_temp = mean_temp.readline().split(',')
while city_temp:
print(headings[0].capitalize(), "of", city_temp[0], headings[2], "is", city_temp[2], "Celsius")
city_temp = mean_temp.readline().split(',')
mean_temp.close()
Upvotes: 1
Views: 143
Reputation: 82899
When you hit the empty last line, i.e. ''
, the result of mean_temp.readline().split(',')
is ['']
, not []
, hence your loop continues and you get the index error. You could check the len
instead:
while len(city_temp) == 4:
print(headings[0].capitalize(), "of", city_temp[0], headings[2], "is", city_temp[2], "Celsius")
city_temp = mean_temp.readline().split(',')
However, the better way to handle this would be with a proper for
loop and csv
reader:
import csv
with open('mean_temp.txt') as f:
reader = csv.reader(f)
header = next(reader)
for city in reader:
print(header[0].capitalize(), "of", city[0], header[2], "is", city[2], "Celsius")
(The file format would work even better with a DictReader
, but the way you print that line doesn't.)
Upvotes: 0
Reputation: 1378
I've tested this and it should work. I think your while clause isn't correctly finding the end of the file - a for loop works and is cleaner.
with open("mean_temp.txt", "a") as f:
f.write("\nRio de Janeiro,Brazil,30.0,18.0")
with open("mean_temp.txt", "r") as f:
headings = f.readline().split(',')
for next_line in f:
next_line = next_line.split(',')
print(headings[0].capitalize(), "of", next_line[0], headings[2], "is", next_line[2], "Celsius")
Upvotes: 1