python读取csv时keyerror_python – 使用DictReader()时的KeyError

您的标题行未使用标签.

当我在没有制表符的情况下重新创建数据时,csv模块返回的行只包含一个(长)键.如果我用实际标签重新创建它,那么我得到:

>>> source_file = open('out.csv', 'rb')

>>> reader = csv.DictReader(source_file, delimiter = '\t')

>>> line = reader.next()

>>> len(line)

37

>>> line.keys()

['Id', '..Easting', '.NE_Err', 'uSt', 'SeiMoment', 'MaxDispla', 'tSt', 'Ns', 'Nt', 'Nu', '.Northing', '.DD_Err', '...Energy', '....uMag', 'V2.0..', 'DyStressD', 'SRC', 'PeakAccPa', '.SourceRo', '........Time', '.EE_Err', 'T', 'Velocity', 'PeakVelPa', 'AspRadius', '...Depth', 'PSt', '....tMag', '.MomMag', 'AppStress', '...Es/Ep', '.ED_Err', 'Event', '.ND_Err', 'Conf', '.StaticSD', '.NN_Err']

>>> line['........Time']

'ND'

>>> line['.Northing']

'746.45'

请注意,这些值不需要剥离;该模块为您处理无关的空白.

您可以单独读取标题,清理它,然后使用csv模块处理其余数据:

source_file = open(NNSRC, 'rb')

header = source_file.readline()

source_file.seek(len(header)) # reset read buffer

headers = [h.strip('.') for h in header.split()]

headers = ['Date'] + headers[2:] # Replace ['SRC', 'V2.0'] with a Date field instead

for line in csv.DictReader(source_file, fieldnames=headers, delimiter = '\t'):

# process line

上面的代码分别读取标题行,拆分它并删除额外的.您可以通过重置readline缓冲区(.seek()调用的副作用)来为更多可行的列键创建句点,然后为DictReader设置文件.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值