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

官方解释请看:

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

#!/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

打印结果:

python判断两个文件是否相同

相关文章:

  • 2022-12-23
  • 2021-09-22
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-03-02
  • 2022-12-23
  • 2022-01-03
猜你喜欢
  • 2021-11-18
  • 2021-07-24
  • 2021-03-31
  • 2022-12-23
  • 2021-07-29
  • 2021-06-06
  • 2021-11-28
相关资源
相似解决方案