Python 标准库内置了一个 difflib 模块,使用它能很轻松的完成文件内容差异的比对。
话不多说直接上示例:
import difflib
conf1_text = '''\
server {
listen 0.0.0.0:80;
charset utf-8;
autoindex_exact_size off;
location / {
root /Volumes/zzeDisk;
index home.html;
autoindex on;
}
}
'''
conf2_text = '''\
server {
listen 0.0.0.0:81;
charset utf-8;
autoindex_exact_size off;
location / {
root /Users/zhangzhongen/Desktop;
index home.html;
autoindex on;
}
}
'''
conf1_lines = conf1_text.splitlines()
conf2_lines = conf2_text.splitlines()
d = difflib.Differ()
diff = d.compare(conf1_lines,conf2_lines)
print('\n'.join(list(diff)))
'''
server {
- listen 0.0.0.0:80;
? ^
+ listen 0.0.0.0:81;
? ^
charset utf-8;
autoindex_exact_size off;
location / {
- root /Volumes/zzeDisk;
+ root /Users/zhangzhongen/Desktop;
index home.html;
autoindex on;
}
}
'''
评论区