Jassi
Jassi

Reputation: 11

Comparing two text files in python and print the difference in two files with command run on the device

I am new to Python. I had written the script to fetch the data from juniper devices and output is like:

Output contains output data from show version and this command is included as well.I am fine until this point.I am facing issues with comparing two text files line by line and printing the difference.

Requirement is to print the difference under every command suppose show version if there is no difference between the file then it should print there is no difference. if there is any thing changed in 2nd file . It should print that difference

Thanks in advance!!

Upvotes: 0

Views: 2007

Answers (1)

Łukasz Rogalski
Łukasz Rogalski

Reputation: 23223

You may use difflib.

This module provides classes and functions for comparing sequences. It can be used for example, for comparing files, and can produce difference information in various formats, including HTML and context and unified diffs.

unified_diff() may be helpful.

difflib.unified_diff(a, b[, fromfile][, tofile][, fromfiledate][, tofiledate][, n][, lineterm])

Compare a and b (lists of strings); return a delta (a generator generating the delta lines) in unified diff format.

import os
import difflib

with open('a.txt', 'rb') as f:
    a = f.readlines()

with open('a.txt', 'rb') as f:
    b = f.readlines()

print os.linesep.join(difflib.unified_diff(a,b))

Sample output, from docs

@@ -1,4 +1,4 @@
-bacon
-eggs
-ham
+python
+eggy
+hamster
 guido

Upvotes: 1

Related Questions