简体   繁体   中英

Python : Compare CSV files and save the difference with first row(Column Names)

I have two CSV files as shown below:

File 1 : June_01_2018.csv

在此处输入图片说明

File 2 : June_02_2018.csv

在此处输入图片说明

Note : I want to find the difference between these two file and store it into the third file with the column headers .

My try :

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)

But unable to store the column headers into the third file.

try this:

    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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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