Reputation: 59
I have below test files
testfile1 output:
put returns between paragraphs
for linebreak add 2 spaces at end
indent code by 4 spaces
testfile2 output:
put returns between paragraphs
for linebreak add 2 spaces at end
indent code by 4 spaces
#commented out
I want to compare two files and print only difference output. If any comments in start of line ignore to compare those line.
Below is code i tried:
import difflib
with open('testfile1') as text1, open('testfile2') as text2:
diff = difflib.ndiff(text1.readlines(), text2.readlines())
with open('diff.txt', 'w') as result:
for line in diff:
result.write(line)
output:
put returns between paragraphs
for linebreak add 2 spaces at end
indent code by 4 spaces
+ #commented
Expected output:
put returns between paragraphs
for linebreak add 2 spaces at end
indent code by 4 spaces
and print "No changes"
Upvotes: 0
Views: 1702
Reputation: 168626
I would eliminate the #
-marked lines using a list comprehension:
...
with open('testfile1') as text1, open('testfile2') as text2:
diff = difflib.ndiff(
[line for line in text1 if not line.startswith('#')],
[line for line in text2 if not line.startswith('#')]
)
...
Upvotes: 1