【问题标题】:Compare two csv files, print out differences in a csv but if difference print all with the same name比较两个 csv 文件,打印出 csv 中的差异,但如果差异打印全部同名
【发布时间】:2020-02-06 12:06:08
【问题描述】:

类似于here 的问题,我需要比较两个 CSV 文件并打印出更改。如果我有一个具有此名称的数字输入,则与此问题的唯一区别是我想将它们全部写入 Differences.csv 文件。我使用的代码与上面的链接相同:

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) 

下面是我想要的输出示例:

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

因此,随着苹果宽度的变化,我想再次打印两个苹果。非常感谢

【问题讨论】:

    标签: python csv compare


    【解决方案1】:

    分两步做这件事感觉很自然:

    • 根据链接中的描述生成名称列表
    • 然后从列表中复制所有带有名称的行

    【讨论】:

    • 谢谢。我一直在考虑这样做,但我一直坚持在输出文件中也有葡萄。
    猜你喜欢
    • 2013-06-17
    • 2016-12-24
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    • 2019-05-15
    • 2019-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多