python比较两个csv文件的dict读取器元素 [英] python compare dict reader elements from two csv files
问题描述
我有两个CSV档案,我想要比较。我已经读了他们使用dict读者。所以现在我有两个CSV文件的字典(每行一个)。我想比较它们,说当两个元素(具有标题h1和h2的元素)相同时,比较这些字典并打印出与第二个字典的差异。以下是示例csv文件。
I have two CSV files that I'm trying to compare. I've read them using dict reader. So now I have dictionaries (one for each row) from two CSV files. I want to compare them, say when two elements (those with headers h1 and h2) are same, compare those dictionaries and print out the differences with respect to the second dictionary. Here are sample csv files.
csv1:
h1,h2,h3
aaa,g0,74
bjg,73,kg9
CSV_new :
h1,h2,h3,h4
aaa,g0,7,
bjg,73,kg9,ahf
我希望输出是这样的,希望它能够在每个字典中打印关于CSV_new的修改,添加和删除:
I want the output to be something like this, though not exactly like shown below, I want it to be able to print out the modifications, additions and deletions in each dictionary with respect to CSV_new:
{h1:'aaa', h2:'g0' {h3:'74', h4:''}}
{h1:'bjg', h2:'73' {h4:''}
我的代码,这不够发达。
My code, that's not well-developed enough.
import csv
f1 = "csv1.csv"
reader1 = csv.DictReader(open (f1), delimiter = ",")
for row1 in reader1:
row1['h1']
#['%s:%s' % (f, row[f]) for f in reader.fieldnames]
f2 = "CSV_new.csv"
reader2 = csv.DictReader(open (f2), delimiter = ",")
for row2 in reader2:
row2['h1']
if row1['h1'] == row2['h1']:
print row1, row2
推荐答案
如果你只是想找到差异,你可以使用difflib
例如:
import difflib
fo1 = open(csv)
fo2 = open(CSV_new)
diff = difflib.ndiff(fo1.readlines(),fo2.readlines())
然后您可以按需要写出差异
If you just want to find difference you can use difflib
As an example:
import difflib
fo1 = open(csv)
fo2 = open(CSV_new)
diff =difflib.ndiff(fo1.readlines(),fo2.readlines())
Then you can write the difference as you want
这篇关于python比较两个csv文件的dict读取器元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!