您使用 csvsniffer 混淆了 csv 阅读器。结果是整行都没有被分成一个元素列表。然后,当您尝试打印(访问)不存在的row
.
只需使用默认值并['
从第一个元素和最后一个元素中手动删除逗号和']
。我的代码假设没有前导或尾随空格;剥去那些他们在那里。
所以,有了这个文件:
$ cat /tmp/dennis.csv
['GB0002875804,ABIH RIAN TCO ORD,"191,560.00000"']
['GB0002374006,DIO ORD 28 101/108P,"440,274.00000"']
['GB00B03MLX29,ROY DUH ELL PLC,"310,437.00000"']
['GB0008762899,BG GP PC OD G0.10,"486,049.00000"']
['GB0008762899,BG GUP C ORD P0.10,"504,867.00000"']
['GB0005405286,BC HL OR D0.50 (K),"1,751,079.00000"']
['GB0009252882,GAITHNE OD P0.25,"806,535.00000"']
['GB00B16GWD56,VNE GRP,"7,254,981.00000"']
这解决了您的问题(据我了解):
import csv
LoL=[]
with open('/tmp/Dennis.csv', 'rb') as csvfile:
reader = csv.reader(csvfile)
try:
for row in reader:
row[0]=row[0].replace("['","")
row[2]=float(row[2].replace("']","").replace(',',''))
LoL.append(row)
print ''.join('{}[{}]:{} '.format('row',i,e) for i,e in enumerate(row))
except (csv.Error, ValueError) as e:
print 'something bad happened...\ndying now...\n',e
print LoL
印刷:
row[0]:GB0002875804 row[1]:ABIH RIAN TCO ORD row[2]:191560.0
row[0]:GB0002374006 row[1]:DIO ORD 28 101/108P row[2]:440274.0
row[0]:GB00B03MLX29 row[1]:ROY DUH ELL PLC row[2]:310437.0
row[0]:GB0008762899 row[1]:BG GP PC OD G0.10 row[2]:486049.0
row[0]:GB0008762899 row[1]:BG GUP C ORD P0.10 row[2]:504867.0
row[0]:GB0005405286 row[1]:BC HL OR D0.50 (K) row[2]:1751079.0
row[0]:GB0009252882 row[1]:GAITHNE OD P0.25 row[2]:806535.0
row[0]:GB00B16GWD56 row[1]:VNE GRP row[2]:7254981.0
[['GB0002875804', 'ABIH RIAN TCO ORD', 191560.0], ['GB0002374006', 'DIO ORD 28 101/108P', 440274.0], ['GB00B03MLX29', 'ROY DUH ELL PLC', 310437.0], ['GB0008762899', 'BG GP PC OD G0.10', 486049.0], ['GB0008762899', 'BG GUP C ORD P0.10', 504867.0], ['GB0005405286', 'BC HL OR D0.50 (K)', 1751079.0], ['GB0009252882', 'GAITHNE OD P0.25', 806535.0], ['GB00B16GWD56', 'VNE GRP', 7254981.0]]