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

如何用Python删除文本文件中以特定单词开头的行?

用Python删除文本文件中特定开头的行

直接在for循环里用del line无效的原因是:line只是当前行的临时字符串变量,删除它不会修改原文件或内存中的行集合,文件内容的修改必须通过重新写入过滤后的内容实现。

方法1:一次性读取过滤(适合小文件)

先将文件所有行读入内存,过滤掉目标行后重新写入原文件:

# 读取原文件内容
with open('test.txt', 'r', encoding='utf-8') as f:
    lines = f.readlines()

# 过滤掉以'bee'开头的行(strip()处理行首可能的空格)
filtered_lines = [line for line in lines if not line.strip().startswith('bee')]

# 将过滤后的内容写回原文件
with open('test.txt', 'w', encoding='utf-8') as f:
    f.writelines(filtered_lines)

方法2:逐行处理+临时文件(适合大文件)

如果文件很大,一次性读取会占用过多内存,可以用临时文件逐行写入,最后替换原文件:

import os

temp_filename = 'test_temp.txt'

# 读取原文件,将符合要求的行写入临时文件
with open('test.txt', 'r', encoding='utf-8') as f_in, open(temp_filename, 'w', encoding='utf-8') as f_out:
    for line in f_in:
        if not line.strip().startswith('bee'):
            f_out.write(line)

# 替换原文件(os.replace支持跨平台原子替换)
os.replace(temp_filename, 'test.txt')

补充说明

  • 如果确定目标行的开头没有空格,可以去掉line.strip(),直接用line.startswith('bee')
  • 操作文件时建议指定编码(如encoding='utf-8'),避免不同环境下的编码问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 11:11:20