You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Python对比两个TXT文件仅返回第二个文件的新增内容?

解决方案:提取第二个文件的新增内容

修改后的完整代码

import difflib
import filecmp
import sys
import requests

# 读取两个文件内容
with open('file1.txt', encoding='utf8') as file_1: 
    file_1_text = file_1.readlines() 

with open('file2.txt', encoding="utf8") as file_2: 
    file_2_text = file_2.readlines() 

# 检查文件是否完全一致
if filecmp.cmp('file1.txt', 'file2.txt'):
    print("Equal")
    sys.exit(1)
else:
    print("different")  
    new_lines = []
    # 遍历差异结果,仅保留第二个文件的新增内容行
    for line in difflib.unified_diff(
            file_1_text, file_2_text, fromfile='file1.txt',  
            tofile='file2.txt', n=0, lineterm=''): 
        # 过滤删除行、标记行和文件头,只保留真正的新增内容
        if line.startswith('+') and not line.startswith('+++'):
            print(line)
            new_lines.append(line)
    
    # Telegram消息发送函数
    def telegram_bot_sendtext(bot_message):
        bot_token = 'YOUR TOKEN'
        bot_chatID = 'YOUR CHAT ID'
        send_text = f'https://api.telegram.org/bot{bot_token}/sendMessage?chat_id={bot_chatID}&parse_mode=Markdown&text={bot_message}'
        response = requests.get(send_text)
        return response.json()

    # 若有新增内容,拼接完整消息后发送
    if new_lines:
        full_message = "different\n" + "\n".join(new_lines)
        telegram_bot_sendtext(full_message)

sys.exit(1)

关键修改说明

  1. 新增内容过滤:通过line.startswith('+') and not line.startswith('+++')的判断,排除掉difflib.unified_diff输出的文件头(如+++ file2.txt)、删除行(-开头)和标记行(@@开头),仅保留第二个文件的新增内容行。
  2. 内容收集与发送:用new_lines列表收集所有新增行,避免原代码中仅发送最后一行的问题;将"different"和所有新增行拼接成完整消息后再调用Telegram接口,确保内容完整。
  3. 代码结构优化:调整了文件比较逻辑的缩进,使用f-string简化URL拼接,提升代码可读性和维护性。

内容的提问来源于stack exchange,提问作者David

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 13:36:11