【问题标题】:Index error of CSV List in Python, even after getting outputPython中CSV列表的索引错误,即使在获得输出之后
【发布时间】:2019-10-21 16:09:08
【问题描述】:

这是一个以列表形式读取csv文件的简单程序,程序可以按索引打印,但最后出现索引错误


import csv

with open('file.csv','r') as f:
    reader = csv.reader(f)
    for r in reader:
        lis = list(r)
        print (lis)
        file_dat  = lis[0]
        file_no   = lis[1]
        content    = lis[2]
        print (file_dat)
        print ("File Data Read Successful")
f.close()

我得到的这个程序的输出是


['ASFDASD', '2019-10-19', 'horse']
ASFDASD
File Data Read Successful
[]
Traceback (most recent call last):
  File "C:\Users\KIRA\AppData\Local\Programs\Python\Python37-32\direction.py", line 14, in <module>
    file_dat  = lis[0]
IndexError: list index out of range

【问题讨论】:

  • 先检查list是否不为空且长度为3

标签: python python-3.x list csv


【解决方案1】:

看起来您的代码正在将输入文件的最后一行读取为一个完全空的行,从而导致一个空列表。这个空列表打印在File Data Read Successful 的正下方。

也许在打印之后但在分配之前检查以确保列表不为空?

import csv

with open('file.csv','r') as f:
    reader = csv.reader(f)
    for r in reader:
        lis = list(r)
        if(lis.len() = 3):
          print (lis)
          file_dat  = lis[0]
          file_no   = lis[1]
          content    = lis[2]
          print (file_dat)
          print ("File Data Read Successful")
f.close()

【讨论】:

    【解决方案2】:

    你最后一个 lis 是空的,你正在尝试访问 lis[0]。 首先通过if lis:检查列表不为空

    【讨论】:

      猜你喜欢
      • 2018-12-03
      • 2015-02-11
      • 1970-01-01
      • 2022-08-11
      • 1970-01-01
      • 2022-01-17
      • 2021-05-12
      • 1970-01-01
      • 2021-01-24
      相关资源
      最近更新 更多