简体   繁体   中英

csv, IndexError: list index out of range

I am reading and doing examples from the book Python Crash Course . Now I get stuck in reading data from a csv file. I'm trying to get values of max_temperatures and read it, but when I did this in the same way as in my book then an error is shown:

IndexError:
high = int(row[1])
IndexError: list index out of range

Code:

import csv


filename = "sitka_weather_history_2014.csv"
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)
    highs = []
    for row in reader:
        high = int(row[1])
        highs.append(high)

    print(highs)

is high the first element in the row? If so, remember that Python starts counting from 0 - so it should be high = int(row[0])

Since the input file contains empty lines, you have to make sure that the list ( row ) is not empty. If it is empty - just skip it.

Something like:

for row in reader:
    if row:
        high = int(row[1])
        highs.append(high)

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