侧边栏壁纸
博主头像
张种恩的技术小栈博主等级

行动起来,活在当下

  • 累计撰写 748 篇文章
  • 累计创建 65 个标签
  • 累计收到 39 条评论

目 录CONTENT

文章目录

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

zze
zze
2020-08-08 / 0 评论 / 0 点赞 / 459 阅读 / 1040 字

不定期更新相关视频,抖音点击左上角加号后扫一扫右方侧边栏二维码关注我~正在更新《Shell其实很简单》系列

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

评论区