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

Python如何按指定标识将文本片段从源文件移动到目标文件指定位置

实现方案

核心逻辑

  • 读取源文件File1.txt,捕获#1到#2两个标记之间的内容,忽略标记外的其他内容
  • 读取目标文件File2,将文件内#1与#2之间的原有内容替换为从源文件提取的片段,其他内容保持不变
  • 将修改后的内容写回目标文件

完整Python代码

# 提取File1中#1和#2之间的内容
extract_content = []
capture = False
with open("File1.txt", "r", encoding="utf-8") as f1:
    for line in f1:
        stripped_line = line.strip()
        if stripped_line == "#1":
            capture = True
            continue
        if stripped_line == "#2":
            capture = False
            break
        if capture:
            extract_content.append(line)

# 替换File2中#1和#2之间的内容
output_lines = []
replace = False
with open("File2", "r", encoding="utf-8") as f2:
    for line in f2:
        stripped_line = line.strip()
        if stripped_line == "#1":
            output_lines.append(line)
            # 插入提取到的内容
            output_lines.extend(extract_content)
            replace = True
            continue
        if stripped_line == "#2":
            output_lines.append(line)
            replace = False
            continue
        if not replace:
            output_lines.append(line)

# 写回File2
with open("File2", "w", encoding="utf-8") as f2:
    f2.writelines(output_lines)

注意事项

  • 代码默认使用utf-8编码读取和写入文件,若你的文件使用其他编码可自行修改encoding参数
  • 若源文件或目标文件中不存在#1/#2标记,代码不会做任何修改,不会破坏原有文件内容
  • 执行脚本前建议提前备份File2文件,避免误操作导致内容丢失

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 14:36:05