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

Python如何删除TXT文件中数量动态变化的冗余行并保留指定内容

解决方案

你当前的问题是硬编码了截取位置N,无法适配冗余行数量动态变化的场景,只要动态定位Header2行的索引即可实现需求。

单文件调整后代码

with open('File1.txt', 'r', encoding='utf-8') as old, open('new_file1.txt', 'w', encoding='utf-8') as new:
    lines = old.readlines()
    # 保留Header1行
    new.write(lines[0])
    # 动态查找Header2所在的行索引
    header2_idx = None
    for idx, line in enumerate(lines):
        if line.startswith('Header2,'):
            header2_idx = idx
            break
    # 写入Header2及之后所有内容
    if header2_idx is not None:
        new.writelines(lines[header2_idx:])

多文件批量处理代码

如果需要处理大量同规则文件,可以用glob批量匹配处理:

import glob
import os

# 匹配规则可根据你的文件命名规则调整,这里默认匹配所有File开头的txt文件
for src_path in glob.glob('File*.txt'):
    # 生成新文件名
    file_name = os.path.basename(src_path)
    dst_path = f'processed_{file_name}'
    
    with open(src_path, 'r', encoding='utf-8') as old, open(dst_path, 'w', encoding='utf-8') as new:
        lines = old.readlines()
        new.write(lines[0])
        header2_idx = None
        for idx, line in enumerate(lines):
            if line.startswith('Header2,'):
                header2_idx = idx
                break
        if header2_idx is not None:
            new.writelines(lines[header2_idx:])

如果Header2的行规则更复杂,你也可以把startswith的匹配逻辑替换为正则匹配,适配更多场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 05:54:03