Home > other >  Compare two source code files and report differences in python
Compare two source code files and report differences in python

Time:12-07

Let's suppose there are two source code files written in Javascript (file1.js and file2.js). I want to compare them using python and spot the different portions of code found in file1, which are not present in file2 (basically the different lines of code found in file1).

How to do it in an efficient way?

CodePudding user response:

  1. Using difflib library: Python has a Module which is specially used for comparing the differences between the files. To get differences using the difflib library, we have to call the unified_diff() function to this comparison.

There is one Class available for comparing the differences between the files which named as Differ inside the difflib library.

You can try any of the above I guess both works fine, just import the library first like from difflib import Differ

from difflib import Differ
  
with open('file1.txt') as file_1, open('file2.txt') as file_2:
    differ = Differ()
  
    for line in differ.compare(file_1.readlines(), file_2.readlines()):
        print(line)

CodePudding user response:

In bash you can run the command diff with two files as command line arguments and it will tell you the difference between the two. So do this below in the terminal.

diff fileOne.js fileTwo.js
  • Related