首页 > 解决方案 > 如何通过python比较2个CSV文件的特定列

问题描述

Python 版本 - 2.6.6

1.csv

10.10.1.1,Web server,test,http,Running
10.10.1.1,Web server,test,http1,Running

2.csv

10.10.1.1,Web server,test,http,Not Running
10.10.1.1,Web server,test,http1,Not Running

我尝试使用下面的代码来比较特定列的 2 个 csv 文件,但它不起作用。我需要根据实际结果输出,请在下面指导

import csv
s=open('1.csv')
checkit = csv.reader(s)
for c in checkit:
    o=open('2.csv')
    csv_o = csv.reader(o)
    for row in csv_o:
        if (row[4] == c[4]) and (row[0] == c[0]):
            print 'equal =',row[0],',',row[3],',',row[4]
        else:
            print 'Differenece =',row[0],',',row[3],',',row[4]

实际结果是

Difference = 10.10.1.1, http,Not Running
Difference = 10.10.1.1, http1,Not Running
Difference = 10.10.1.1, http,Not Running
Difference = 10.10.1.1, http1,Not Running

预期的结果是

Difference = 10.10.1.1, http,Not Running
Difference = 10.10.1.1, http1,Not Running

需要在不同的 csv 中写入预期结果。请帮忙

标签: csvcomparisonpython-2.6

解决方案


推荐阅读