仅需完成2项准备即可启动搭建流程:
将以下完整代码粘贴至compare_archives.py文件,无需任何修改:
```python import difflib import os import sys def compare_archives(file1_path, file2_path): 校验文件有效性 if not os.path.isfile(file1_path): print(f"错误:版本1路径不存在:{file1_path}") return False if not os.path.isfile(file2_path): print(f"错误:版本2路径不存在:{file2_path}") return False try: 读取文件内容,适配多编码 with open(file1_path, 'r', encoding='utf-8', errors='ignore') as f1, \ open(file2_path, 'r', encoding='utf-8', errors='ignore') as f2: lines1 = f1.readlines() lines2 = f2.readlines() except Exception as e: print(f"读取文件失败:{str(e)}") return False 生成统一格式的差异对比结果 diff_output = difflib.unified_diff( lines1, lines2, fromfile="版本1档案", tofile="版本2档案", lineterm="" ) 保存对比结果到本地 result_path = os.path.join(os.getcwd(), "档案差异结果.txt") try: with open(result_path, 'w', encoding='utf-8') as f: f.write("\n".join(diff_output)) print(f"对比完成!差异结果已保存至:{result_path}") return True except Exception as e: print(f"写入结果失败:{str(e)}") return False if __name__ == "__main__": 获取用户输入的两个档案路径 file1 = input("请输入版本1档案的完整路径:").strip().strip('"') file2 = input("请输入版本2档案的完整路径:").strip().strip('"') if not file1 or not file2: print("错误:文件路径不能为空!") sys.exit(1) compare_archives(file1, file2) ```将需对比的两个档案(支持txt、md、json等纯文本格式)放入本地任意文件夹,复制它们的完整路径:

打开终端工具(Windows按Win+R输入cmd回车;Mac按Command+空格输入terminal回车;Linux直接打开终端),执行以下操作:
按脚本提示依次输入两个档案的完整路径,回车后等待结果生成:
若需对比json、xml等结构化档案,修改脚本的文件读取逻辑即可,以下为json适配的修改代码:
```python 在脚本开头新增导入json模块 import json 替换原有文件读取逻辑,新增结构化文件读取函数 def read_structured_file(path): json文件格式化后对比 if path.endswith('.json'): with open(path, 'r', encoding='utf-8') as f: return json.dumps(json.load(f), indent=2).splitlines() 原有txt/md等普通文件读取逻辑不变 else: with open(path, 'r', encoding='utf-8', errors='ignore') as f: return f.readlines() 将compare_archives函数中的lines1/lines2赋值语句修改为: lines1 = read_structured_file(file1_path) lines2 = read_structured_file(file2_path) ```