0

我有一个像这样的csv:

"Equipment","LNKEQP","METAST","METSER","MODSTA","METEOD"
"HLL_POS_00098",1,1,0,0,0
"TOY_GAT_00003",0,0,0,3,0
"NAT_POS_00010",0,3,0,3,0
"NAT_GAT_00002",0,0,0,0,0
"NAT_GAT_00001",0,0,0,4,0
A machine A is unavailable

我使用代码将该 csv 文件读取为:

reader = csv.DictReader(f)
s=[]
for row in reader:

但该行不包含“A 机器 A 不可用”,如何获取该行并输出如下示例:

'METEOD': '0', 'MODSTA': '0', 'METSER': '0', 'LNKEQP': '0', 'METAST': '0', 'Equipmnt': 'NAT_VCF_00001'
'METEOD': '0', 'MODSTA': '0', 'METSER': '0', 'LNKEQP': '1', 'METAST': '1', 'Equipment': 'NAT_TVM_00002'
A machine A is unavailable

感谢您的帮助

4

1 回答 1

4

在解析它们之前删除有问题的行:

import csv
from StringIO import StringIO

i = """"Equipment","LNKEQP","METAST","METSER","MODSTA","METEOD"
"HLL_POS_00098",1,1,0,0,0
"TOY_GAT_00003",0,0,0,3,0
"NAT_POS_00010",0,3,0,3,0
"NAT_GAT_00002",0,0,0,0,0
"NAT_GAT_00001",0,0,0,4,0
A machine A is unavailable
"""

# Take only those lines that contain a comma.
j = "".join([line for line in StringIO(i).readlines() if ',' in line])

# Parse the taken lines as CSV.
reader = csv.reader(StringIO(j))
for line in reader:
    print line

输出:

['Equipment', 'LNKEQP', 'METAST', 'METSER', 'MODSTA', 'METEOD']
['HLL_POS_00098', '1', '1', '0', '0', '0']
['TOY_GAT_00003', '0', '0', '0', '3', '0']
['NAT_POS_00010', '0', '3', '0', '3', '0']
['NAT_GAT_00002', '0', '0', '0', '0', '0']
['NAT_GAT_00001', '0', '0', '0', '4', '0']
于 2012-11-12T10:48:36.123 回答