Python – Compare Two Different files line-by-line

Python Compare Two Different files line by line

Today in this article, we will learn a simple and easy approach In Python – Compare Two Different files line-by-line.

There are multiple ways available for comparing the file and getting differences or getting common lines.

This step-by-step article demonstrates how to compare two files to see if their contents are different and if they are different then we will get the file of differences.

This comparison looks at the contents of the two files and checks each line by line with any order which may or may not match with other files like the file metadata including names, locations, times, or other attributes.

Python supports multiple modules to find differences or common.

File A – We have the below file with the content.

Python - Compare Two Different files line-by-line, python compare two files for differences,
Compare two Files line by line in Python 1

File B – We have the below file with the content different from the previous file as highlighted.

compare two files and print unmatched lines in python
Compare two different files line by line in python 1

Python Code

filenameA = "C:\Test\FileA.txt"
filenameB =  "C:\Test\FileB.txt"


with open(filenameA, 'r') as fileA:
    with open(filename2, 'r') as fileB:
        same = set(fileA).difference(fileB)


same.discard('n')

with open('FileC.txt', 'w') as file_out:
    for line in same:
        file_out.write(line)

Output

Once the code is executed, you shall see the file is generated with only delta changes having the differences i.e return all the elements which exist in File A but don’t in File B.

python compare two files character by character
python compare two files word by word 3

27 APOSTROPHE A7 SECTION SIGN
23 NUMBER SIGN A3 POUND SIGN

You can swap the baseline file as required for example as below,

    same = set(fileB).difference(fileA)

Above find the records which exist in File B but doesn’t available in File A

27  APOSTROPHE                  A7  SECTION SIGNATURE
23  NUMBER SIGN                 A3  DOLAAR SIGN

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *