简体   繁体   English

比较两个 csv 文件,打印出 csv 中的差异,但如果差异打印所有同名

[英]Compare two csv files, print out differences in a csv but if difference print all with the same name

Similar to the the question here , I need to compare two CSV files and print out the changes.这里的问题类似,我需要比较两个 CSV 文件并打印出更改。 The only difference to this question if I have a number inputs with this name I want to write them all to the Differences.csv file.如果我有一个具有此名称的数字输入,这个问题的唯一区别是我想将它们全部写入 Differences.csv 文件。 I'm using the same code as the link above:我使用与上面链接相同的代码:

with open('old_file.csv','rb') as file1:
   existingLines = [line for line in csv.reader(file1, delimiter=',')]

   with open('new_file.csv','rb') as file2:
       reader2 = csv.reader(file2,delimiter=',')

       with open('Differences.csv', 'wb') as h:
           writer = csv.writer(h)

           for row in reader2:
               if row not in new and row not in existingLines:
                   new.append(row) 

I've an example below of the output I want below:我在下面有一个我想要的输出示例:

old_file =                          new_file = 
Fruit Length Width                  Fruit Length Width
Grape  0.3    0.4                   Grape  0.3    0.4
Grape  0.2    0.5                   Grape  0.2    0.5
Apple  0.8    1.0                   Apple  0.8    1.0
Apple  1.0    1.1                   Apple  1.0    1.0
                                    Plum   1.3    1.4
                                    Plum   1.1    1.2

Differences = 
Fruit Length Width 
Apple  0.8    1.0
Apple  1.0    1.0
Plum   1.3    1.4
Plum   1.1    1.2

So as the apples width has changed I want to print both apples again.因此,随着苹果宽度的变化,我想再次打印两个苹果。 Many thanks非常感谢

It feels natural to do it in two steps:分两步做感觉很自然:

  • Generate a list of names with changes as described in link如链接中所述,生成具有更改的名称列表
  • Then copy all the lines with names from the list然后从列表中复制所有带有名称的行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM