首页 > 解决方案 > 特定行 [8] 的 CSV 解析错误:列表索引超出范围

问题描述

我正在尝试从 CSV 文件中获取行值,除了row[8]. 但是同一行就像row[7]我删除它之前的任何其他行一样。

comment = row[8]
IndexError: list index out of range

这是示例 CSV:

190,3391d5ae,,Host-1,FuelNode-1,"http,tcp-8000",False,,created on - 6/10/14
192,25dbbf4c,sam,"vlan85,vlan86","Srv1,Srv2",dhcp-relay,False,25-10-2018,

请注意,很少有字段没有值或空白。

这是我写的代码。

outFiles = os.listdir('datastore/csv_out_files')
ext = "*.csv"  
for csvoutfile in outFiles:
  if fnmatch.fnmatch(csvoutfile, ext):
     with open('datastore/csv_out_files/'+ csvoutfile) as f:
        rows = csv.reader(f, delimiter=',')
        headers = next(rows)
        for row in rows:
            uid = row[1]
            name = row[2]
            source = row[3]
            destination = row[4]
            service = row[5]
            enabled = row[6]
            use_date = row[7]
            comment = row[8]

            if not use_date:
                use_date = "Never Used"

            print "              UID:", (uid)
            print "             Name:", (name)
            print "           Source:", (source)
            print "      Destination:", (destination)
            print "          Service:", (service)
            print "          Enabled:", (enabled)
            print "        Last Used:", (use_date)
            print "  Additional Info:", (comment)

请帮助我,我无法弄清楚这一点。

标签: pythonpython-2.7csv

解决方案


推荐阅读