
要实现一个简单的 Python 文件对比工具,我们可以通过内置的 difflib 模块来完成。它能帮助我们逐行比较两个文本文件的内容,并输出差异,适合用于检查配置文件、代码版本或日志文件的变化。
difflib 是 Python 标准库中专门用于比较序列(如字符串、列表)差异的模块。我们可以用它来读取两个文件并生成可读性高的对比结果。
以下是一个基础实现:
import difflib
<p>def compare_files(file1, file2):
with open(file1, 'r', encoding='utf-8') as f1, \
open(file2, 'r', encoding='utf-8') as f2:
content1 = f1.readlines()
content2 = f2.readlines()</p><pre class='brush:python;toolbar:false;'># 生成差异
diff = difflib.unified_diff(
content1, content2,
fromfile=file1,
tofile=file2,
lineterm=''
)
return '\n'.join(diff)result = compare_files('file1.txt', 'file2.txt') print(result)
这段代码会输出类似 Git diff 的格式,标出哪些行被添加、删除或修改。
立即学习“Python免费学习笔记(深入)”;
如果想在网页中展示差异,可以使用 difflib.HtmlDiff 生成带颜色标记的 HTML 页面。
本支付接口的特点,主要是用xml文件来记录订单详情和支付详情。代码比较简单,只要将里面的商户号、商户key换成你自己的,将回调url换成你的网站,就可以使用了。通过这个实例也可以很好的了解一般在线支付接口的基本工作原理。其中的pay.config文件记录的是支付详情,order.config是订单详情
0
def compare_to_html(file1, file2, output_html='diff.html'):
with open(file1, 'r', encoding='utf-8') as f1, \
open(file2, 'r', encoding='utf-8') as f2:
content1 = f1.readlines()
content2 = f2.readlines()
<pre class='brush:python;toolbar:false;'>html_diff = difflib.HtmlDiff()
html_result = html_diff.make_file(content1, content2, fromdesc=file1, todesc=file2)
with open(output_html, 'w', encoding='utf-8') as f:
f.write(html_result)
print(f"HTML 差异已保存至 {output_html}")调用 compare_to_html('a.txt', 'b.txt') 后,会生成一个直观的网页,绿色表示新增,红色表示删除。
为了让工具更实用,可以加入命令行参数解析,方便直接运行。
import argparse
<p>def main():
parser = argparse.ArgumentParser(description="简易文件对比工具")
parser.add_argument('file1', help="第一个文件路径")
parser.add_argument('file2', help="第二个文件路径")
parser.add_argument('--html', nargs='?', const='diff.html', help="输出 HTML 差异文件")</p><pre class='brush:python;toolbar:false;'>args = parser.parse_args()
if args.html:
compare_to_html(args.file1, args.file2, args.html)
else:
result = compare_files(args.file1, args.file2)
print(result)if name == 'main': main()
使用方式:
基本上就这些。通过组合 difflib 和文件操作,我们就能快速构建一个轻量但实用的文件对比工具,无需依赖外部包,适合嵌入脚本或自动化流程中。
以上就是Python 文件对比工具的简单实现的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号