python判断两个文件是否相同

2019-07-02 09:25:45 浏览数 (1)

此方法相当于 Linux 系统下的diff,或者是 git 下的 checkout

官方解释请看:

https://docs.python.org/2/library/difflib.html

代码语言:javascript复制
#!/usr/bin/env python
# -*# coding: utf-8 -*-

import difflib

if __name__ == '__main__':
    # .splitlines(True)为保留了rn
    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

打印结果:

0 人点赞