比较两个csv文件,一行代码失败

时间:2016-08-10 10:51:02

标签: python python-3.x csv parsing

我有以下代码(包括完整代码)它负责比较2个csv文件

(我坚持要保持一线格式):

master_indices = dict(((r[0]), i) for i, r in enumerate(csv.reader(master)))

我需要添加声明,如果该行包含' /'比enumarate和make dic

我试过了:

master_indices = dict(((r[0]), i) for i, r in enumerate(csv.reader(master)) if r.startswith('/') )

master_indices = dict(((r[0]), i) for i, r in enumerate(csv.reader(master)) if re.search(r'/', str(r)))

my lines looks like

1/2/3 12:02:03, aaa, 4bb5b, dddd, eeee
2 ----------> dont want this
3/4/8 1:01:54, aaa, rrrr, dddddd, fdghd
3/4/8 1:01:54  aah, 12rr, ddghddd, fdghd
3/4/8 1:01:54  agy, rr34r, ddhgdd, fdghd
47,    23,    54 ---> dont want this

完整代码: import csv

with open('C:\\Users\\Fradad\\Desktop\\work\\New folder (2)\\NPPD-conversion\\HIS_exp_20140101\\LTA\\LTA37\\Analog_per_5_min_20140101.csv', 'r') as master:
    master_indices = dict(((r[0]), i) for i, r in enumerate(csv.reader(master)) if re.search(r'/', str(r)))


with open('C:\\Users\\Fradad\\Desktop\\work\\New folder (2)\\NPPD-conversion\\HIS_exp_20140101\\LTA\\LTA37\\Analog_exp_2014010100.csv', 'r') as hosts:
    with open('results1.csv', 'w') as results:
        reader = csv.reader(hosts)
        writer = csv.writer(results)

        writer.writerow(next(reader, []) + ['RESULTS'])

        for row in reader:
            index = master_indices.get(row[0])
            if index is not None:
                message = 'FOUND in master list (row {})'.format(index)
            else:
                message = 'NOT FOUND in master list'
            writer.writerow(row + [message])

1 个答案:

答案 0 :(得分:0)

你试过这个吗?

master_indices = {r[0]:i for i,r in enumerate(csv.reader(master)) if "/" in r[0]}

如果你想在所有的行中找到“/”,你可以这样做:

 master_indices = {r.split(",",1)[0]:i for i,r in enumerate(master) if "/" in r}