打印python difflib文件中的行数

时间:2016-03-09 10:09:52

标签: python diff difflib

我试图在Python中使用difflib找到2个文本文件之间的区别。我可以打印已在新文件中添加或删除的文本。但是我想在哪条线上进行修改。即使我知道如何计算文件中的行数,我也无法打印已添加或删除的行。我的代码在这里:

import difflib
import time


def get_diff(old_file, new_file):
    f1 = open(old_file, 'r')
    f2 = open(new_file, 'r')

    old_file = f1.readlines()
    new_file = f2.readlines()

    diff = difflib.unified_diff(old_file, new_file, lineterm='')
    lines = list(diff)[2:]
    added = [lineA for lineA in lines if lineA[0] == '+']


    with open("output.txt", "w") as fh1:
     for line in added:
       fh1.write(line)
    print '+',added
    removed = [lineB for lineB in lines if lineB[0] == '-']
    with open("output.txt", "a") as fh1:
     for line in removed:
       fh1.write(line)
    print '-',removed


if __name__ == '__main__':
    fh = get_diff("ex.txt","ex2.txt")

提前谢谢你:)

1 个答案:

答案 0 :(得分:0)

unified diff已包含有关不同行的信息:

--- before.py
+++ after.py
@@ -1,4 +1,4 @@
-bacon
-eggs
-ham
+python
+eggy
+hamster
 guido

第三行@@ -1,4 +1,4 @@告诉您更改的位置。