I am trying to compare two files using difflib. After comparing I want to print "No Changes" if no difference detected. If difference is their in some lines. I want to print those line.
I tried like this:
with open("compare.txt") as f, open("test.txt") as g:
flines = f.readlines()
glines = g.readlines()
d = difflib.Differ()
diff = d.compare(flines, glines)
print("\n".join(diff))
It will print the contents of the file if "no changes" are detected. But I want to print "No Changes" if there is no difference.
Check to see if the first character in each element has a +
or -
at the start (marking the line having changed):
with open("compare.txt") as f, open("test.txt") as g:
flines = f.readlines()
glines = g.readlines()
d = difflib.Differ()
diffs = [x for x in d.compare(flines, glines) if x[0] in ('+', '-')]
if diffs:
# all rows with changes
else:
print('No changes')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.