简体   繁体   English

csv,IndexError:列表索引超出范围

[英]csv, IndexError: list index out of range

I am reading and doing examples from the book Python Crash Course . 我正在阅读Python速成课程并在其中做示例。 Now I get stuck in reading data from a csv file. 现在,我陷入了从csv文件读取数据的困境。 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: 我试图获取max_temperatures值并读取它,但是当我以与本书相同的方式进行此操作时,将显示错误:

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? high是该行的第一个元素? If so, remember that Python starts counting from 0 - so it should be high = int(row[0]) 如果是这样,请记住Python从0开始计数-因此它应该为high = int(row[0])

Since the input file contains empty lines, you have to make sure that the list ( row ) is not empty. 由于输入文件包含空行,因此您必须确保列表( row )不为空。 If it is empty - just skip it. 如果为空-跳过它。

Something like: 就像是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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