Skip to content
Advertisement

Get a specific line before specific line in txt file after comparison

I’m doing comparison between 2 txt files and i want to add before the difference lines the name of interface which contains this line to be like below :.

First file contains :

JavaScript

Second file contains :

JavaScript

Code is as below :

JavaScript

code result is like below :

JavaScript

The code result which i need to be :

JavaScript

Advertisement

Answer

It’s not necessary to reimplement algorithm to find differences, you can use difflib.ndiff(), just some preparation required. We need to pass to ndiff() only lines which belongs to interface.

We can use generator function which returns interface name and all lines belongs to this interface:

JavaScript

Then we just open both files and iterate over them using our generator function. If interface names are equal in both files we simply pass lines to ndiff() and print only differences:

JavaScript

Using two file samples you provided you will get next output:

JavaScript

P.S. Using generator function allows you to not keep entire file content in memory, so this method should work fine with large files.

Advertisement