使用Python完成文件内容的差异比对

使用Python完成文件内容的差异比对

微信搜索 zze_coding 或扫描 👉 二维码关注我的微信公众号获取更多资源推送:

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;
  	}
  }
'''

Copyright: 采用 知识共享署名4.0 国际许可协议进行许可

Links: https://www.zze.xyz/archives/python-difflib.html

Buy me a cup of coffee ☕.