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

如何在Python中查找文本文件中的特定字符串

如何在Python中查找文本文件里的特定字符串?

Hey there! Let's break down how to hunt for specific strings in your DATA.txt file using Python, especially since you've got that clipboard-monitoring code running already.

方法1:读取整个文件内容查找(适合小文件)

如果你的DATA.txt不会特别大,直接把整个文件内容读进内存查找是最省心的方式。比如要找"Entry Short"这类目标字符串:

filepath = r"C:\Users\BOT\Desktop\DATA.txt"
target_str = "Entry Short"

# 读取整个文件内容
with open(filepath, 'r') as f:
    file_content = f.read()

if target_str in file_content:
    print(f"找到目标字符串:{target_str}")
    # 还能获取首次出现的位置
    first_pos = file_content.find(target_str)
    print(f"首次出现位置:{first_pos}")
else:
    print(f"没找到目标字符串:{target_str}")

方法2:逐行查找(适合大文件)

要是DATA.txt后期会变得很大,逐行读取能节省内存,还能精准定位目标所在的行号:

filepath = r"C:\Users\BOT\Desktop\DATA.txt"
target_str = "Exit Long"

with open(filepath, 'r') as f:
    line_num = 0
    for line in f:
        line_num += 1
        if target_str in line:
            print(f"在第{line_num}行找到目标字符串!")
            print(f"行内容:{line.strip()}")

结合你的剪贴板监控代码做整合

你的现有代码是持续覆盖写入DATA.txt,如果想每次写入后自动检查特定字符串,可以把查找逻辑直接嵌进循环里:

import pyperclip
import time

filepath = r"C:\Users\BOT\Desktop\DATA.txt"
target_str = "Entry Long"

while True:
    contents = pyperclip.paste()
    # 这里注意:'w'模式会覆盖整个文件,要是想追加内容而非覆盖,改成'a'即可
    with open(filepath, 'w') as f:
        f.write(contents)
    # 写入完成后立即检查目标字符串
    with open(filepath, 'r') as f:
        file_content = f.read()
        if target_str in file_content:
            print(f"检测到目标字符串:{target_str}")
            # 这里可以加你需要的后续操作,比如弹窗提示、记录日志等
        else:
            print("未检测到目标字符串")
    # 加个小延迟,避免循环太占CPU
    time.sleep(0.5)

顺便提一句:你的原代码里用了with open语句,它会自动帮你关闭文件,所以不需要手动调用f.close()哦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:01:46