本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名原文链接~~~

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

如果这篇文章对您有帮助,可点击下方链接分享给你的朋友们😋,如果遇到问题欢迎评论、留言~~~😇

评论

公众号:zze_coding

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×