Yesterday I have been implementing a small Python scripts that checks difference between two files (using difflib), printing the result if there is any, exiting with code 0 otherwise.
The precise method, difflib.unified_diff()
is returning a generator on the diffs found. How can I test this generator to see if it needs to be printed? I tried using len()
, sum()
to see what was the size of this generator but then it is impossible to print it.
Sorry to ask such a silly question but I really don't see what is the good practice on that topic.
So far this is what I am doing
import difflib
import sys
fromlines = open("A.csv").readlines()
tolines = open("B.csv").readlines()
diff = difflib.unified_diff(fromlines, tolines, n=0)
if (len(list(diff))):
print("Differences found!")
# Recomputing the generator again: how stupid is that!
diff = difflib.unified_diff(fromlines, tolines, n=0)
sys.stdout.writelines(diff)
else:
print("OK!")