0
我正試圖在Python中使用difflib來查找2個文本文件之間的差異。我可以打印新文件中添加或刪除的文本。但是我想打印在哪一行進行了修改。即使我知道如何計算文件中的行數,我無法打印已添加或刪除的行。我的代碼是在這裏:打印python difflib文件中的行數
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")
預先感謝您:)
H你能解釋一下嗎?我不明白如何讀取這些數字 –
請參閱https://en.wikipedia.org/wiki/Diff_utility#Unified_format –
Hom謝謝:) –