Python:比较CSV文件并将差异保存在第一行(列名)

时间:2018-06-04 08:52:35

标签: python python-3.x pycharm

我有两个CSV文件,如下所示:

文件1 June_01_2018.csv

enter image description here

文件2 June_02_2018.csv

enter image description here

注意:我想找到这两个文件之间的区别,并将其存储到第三个文件并带有列标题

我的尝试

with open('June_01_2018.csv', 'r') as f1:
    file1 = f1.readlines()

with open('June_02_2018.csv', 'r') as f2:
    file2 = f2.readlines()

with open('June_Updates.csv', 'w') as outFile:
    for line in file2:
        if line not in file1:
            outFile.write(line)

但无法将列标题存储到第三个文件中。

1 个答案:

答案 0 :(得分:2)

试试这个:

    with open('June_01_2018.csv', 'r') as f1:
        file1 = f1.readlines()

    with open('June_02_2018.csv', 'r') as f2:
        file2 = f2.readlines()

    with open('June_Updates.csv', 'w') as outFile:
        outFile.write(file1[0])
        for line in file2:
            if line not in file1:
                outFile.write(line)