侧边栏壁纸
博主头像
张种恩博主等级

一个能运维的 JPG 搬运工

  • 累计撰写 713 篇文章
  • 累计创建 62 个标签
  • 累计收到 33 条评论

目 录CONTENT

文章目录

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

张种恩
2020-08-08 / 0 评论 / 0 点赞 / 343 阅读 / 0 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2020-08-08,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

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

评论区