Solution: How to Compare Two CSV Files

Development | Software Testing
Description
I have two CSV files with the same headers. I'd like to compare these files and return entries that are missing from the second file. Here's an example:

file1.csv
fname,lname,city,state
Joe,Smith,Dallas,TX
Jane,Done,Baltimore,MD
Frank,Jones,Plano,TX

file2.csv
fname,lname,city,state
Joe,Smith,Dallas,TX
Jane,Done,Baltimore,MD


compare.py

import csv
t1 = open('file1.csv', 'r')
t2 = open('file2.csv', 'r')
fileone = t1.readlines()
filetwo = t2.readlines()
t1.close()
t2.close()

outFile = open('update.csv', 'w')
x = 0
for i in fileone:
    if i != filetwo[x]:
        outFile.write(filetwo[x])
    x += 1
outFile.close()

Attachments
No attachments.
Solutions
Where the /v switch returns the differences and /g: gets the search strings from file1.csv. You can use findstr /? for more help.

You can also print the differences to a file using:

findstr /v /g:"file1.csv" "file2.csv > diffs.csv"

As an aside, I found findstr far more accurate and the output more readable than fc.

on July 30th, 2019 (9:03 pm)
What masters said
You must sign in to comment!!
All comments
This solution has not been commented yet.