此方法相当于 Linux
系统下的diff
,或者是 git
下的 checkout
官方解释请看:
#!/usr/bin/env python
# -*# coding: utf-8 -*-
import difflib
if __name__ == '__main__':
# .splitlines(True)为保留了\r\n
a = open("diff1.txt", "r").read().splitlines(True)
b = open("diff3.txt", "r").read().splitlines(True)
# difflib.context_diff(a, b[, fromfile][, tofile][, fromfiledate][, tofiledate][, n][, lineterm])
# fromfile:a的文件名
# tofile:b的文件名
# fromfiledate:a文件的修改时间
# tofiledate:b文件的修改时间
# n:变化那一行前后n行展示,默认n=3
# lineterm:打印出来的换行符,默认为\n
diff = difflib.context_diff(a, b, fromfile='fromfile.txt', tofile='tofile.txt', n=0, lineterm="\n")
result = "".join(diff)
print result
打印结果: