简体   繁体   English

比较python中的两个文件忽略比较注释行

[英]compare two files in python ignore comparing commented lines

I have below test files 我有以下测试文件

testfile1 output: testfile1输出:

   put returns between paragraphs
   for linebreak add 2 spaces at end
   indent code by 4 spaces

testfile2 output: testfile2输出:

   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" 并打印“无更改”

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('#')]
        )
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM