【问题标题】:Python Dict from CSV IndexError来自 CSV IndexError 的 Python 字典
【发布时间】:2014-07-15 20:06:29
【问题描述】:

我需要比较 2 个 CSV 文件,我正在尝试使用 @Martijn Pieters 解决方案 Python: Comparing two CSV files and searching for similar items,但我遇到了错误:

IndexError: list index out of range

这是我正在使用的代码,

import csv
with open('filename.csv', 'rb') as a:
  indices = dict((r[2], i) for i, r in enumerate(csv.reader(a)))
  print indices

filename.csv 有 10 列和 2000 行。我想索引具有主机名的第 3 列,然后与其他 .csv 文件中的主机名匹配

type,id,hostname,os,,,,
phy,123,server1,rhel5,,,,
vir,234,server2,rhel6,,,,

我不确定为什么会收到 IndexError。请帮助解决问题。

【问题讨论】:

  • 是空格还是逗号分隔您的数据,您一分钟前有空格吗?您的代码在您编辑后运行良好。
  • 对不起@PadraicCunningham 我有逗号。

标签: python csv dictionary


【解决方案1】:

您的 csv 文件的开头或结尾可能有空行。

我能够使用以下代码重现此错误:

import csv

with open('filename.csv', 'wb') as a:
    strng = """
type,id,hostname,os,,,,
phy,123,server1,rhel5,,,,
vir,234,server2,rhel6,,,,

"""
    a.write(strng)

with open('filename.csv', 'rb') as a:
    indices = dict((r[2], i) for i, r in enumerate(csv.reader(a)))
    print indices

但是,当我删除这些空白行时,代码运行完美:

import csv

with open('filename.csv', 'wb') as a:
    strng = """type,id,hostname,os,,,,
phy,123,server1,rhel5,,,,
vir,234,server2,rhel6,,,,    
"""
    a.write(strng)

with open('filename.csv', 'rb') as a:
    indices = dict((r[2], i) for i, r in enumerate(csv.reader(a)))
    print indices

有关如何跳过 csv 中的空白行,请参阅此 SO Answer

【讨论】:

  • 谢谢@rvraghav93!就是这样,在文件的底部有几行只有一列。我删除了这些,现在可以正常工作了。
猜你喜欢
  • 2014-09-20
  • 1970-01-01
  • 2021-01-10
  • 2014-05-27
  • 2023-03-15
  • 2017-03-10
  • 2016-03-04
  • 2020-10-30
  • 1970-01-01
相关资源
最近更新 更多