如何通过从“ ndiff”中添加相似的行来获得编辑结果?

时间:2019-02-05 11:32:19

标签: python-3.x python-2.7 difflib

我想从file2更新file1。我想在两个文件中添加相似的行。我使用difflib.ndiff()获得了比较结果。如何添加单独更改的行?

import difflib  

file1='file1.txt'  
file2='file2.txt'

def read():    
    ndiffout=open('diffresult.txt','w+')  
    f1_text=file1.readlines()  
    f2_text=file2.readlines()  
    for line in difflib.ndiff(f1_text,f2_text):  
        print line  
        ndiffout.write(line)

def fetchdiff():  
    ndiffout=open('diffresult.txt','r')  
    lines=ndiffout.readlines()  
    s=''.join([line[0] for line in lines])  
    print s  

read()  
fetchdiff() 

file1.txt

apple  
mango  
orange

file2.txt

aplee  
manngo  
grapes

diffresult.txt

- apple  
?  -  
+ aplee  
?     +  
- mango  
+ manngo  
?   +  
- orange  
+ grapes

预期结果:

apple  
mango  
orange

1 个答案:

答案 0 :(得分:0)

您需要这样的东西

true