python-difflib内置模块之文本对比

1. 什么是difflib? 用来做什么?

difflib为python的标准库模块,无需安装。作用时对比文本之间的差异。
并且支持输出可读性比较强的HTML文档,与LInux下的diff命令相似。
在版本控制方面非常有用。

2. 符号理解

符号 含义
‘-’ 包含在第一个系列行中,但不包含第二个。
‘+’ 包含在第二个系列行中,但不包含第一个。
’ ’ 两个系列行一致
‘?’ 存在增量差异
‘^’ 存在差异字符

文本的比较

import difflib

text1='''1.ntp:x:38:38::/etc/ntp:/sbin/nologin
2.sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
3.tcpdump:x:72:72::/:/sbin/nologin
4.kiosk:x:1000:1000:kiosk:/home/kiosk:/bin/bash
5.apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
'''.splitlines(keepends=True)

text2='''1.ntp:x:38:38::/etc/ntp:/sbin/nologin
3.tcpdump:x:72:72::/:/sbin/nologin
4.kiosk:x:1000:1000:kiosk:/home/kiosk:/bin/bash
5.apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
6.mysql:x:27:27:MariaDB Server:/var/lib/mysql:/sbin/nologin
'''.splitlines(keepends=True)

# d = difflib.Differ()
# print("".join(list(d.compare(text1,text2))))

d=difflib.HtmlDiff()
html=d.make_file(text1,text2)
with open('diff.html','w') as f:
    f.write(html)

在这里插入图片描述
在这里插入图片描述

文件之间的对比

import difflib

file1 = '/etc/passwd'
file2 = '/tmp/passwd'

with open(file1) as f1, open(file2) as f2:
    content1 = f1.read().splitlines(keepends=True)
    content2 = f2.read().splitlines(keepends=True)

d=difflib.HtmlDiff()
html=d.make_file(content1,content2)

with open('passwdDiff.html','w') as f:
    f.write(html)

实现mydiff命令

import difflib
import sys

if len(sys.argv) != 3:
    print("""
      Usage: %s   比较的文件1  比较的文件2  [>导出的文件路径 ]     
    """ %(sys.argv[0]))
else:
    filename1 = sys.argv[1]
    filename2 = sys.argv[2]
    try:
        with open(filename1) as f1, open(filename2) as f2:
            content1 = f1.read().splitlines(keepends=True)
            content2 = f2.read().splitlines(keepends=True)
    except Exception as e:
        print("比较错误, 错误原因: ", e)
    else:
        d = difflib.HtmlDiff()
        htmlContent = d.make_file(content1, content2)
        print(htmlContent)
  
  再在命令行里输入:
  mydiff /etc/passwd /tmp/passwd > /home/kiosk/Desktop/test.html

猜你喜欢

转载自blog.csdn.net/qq_43273590/article/details/86528290