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

如何在不占用大量内存的情况下删除Python文本文件中含指定单词的行

大文件场景下删除含特定单词行的优化方案

你的原代码通过readlines()把所有行加载到数组里,确实在处理大文件时容易触发内存不足问题。下面提供两种无需一次性加载全部内容到内存的实现方式:

方法一:使用临时文件逐行处理

这种方法通过逐行读取原文件,将不需要删除的行写入临时文件,最后替换原文件,全程只在内存中保留当前处理的一行:

import os

word = "five"
temp_file = "test_temp.txt"

try:
    # 逐行读取原文件,写入符合条件的行到临时文件
    with open("test.txt", "r") as src, open(temp_file, "w") as dst:
        for line in src:
            if word not in line:
                dst.write(line)
    # 用临时文件替换原文件(跨平台安全)
    os.replace(temp_file, "test.txt")
except FileNotFoundError:
    print("文件不存在!")
except Exception as e:
    print(f"处理出错:{e}")
    # 出错时清理临时文件
    if os.path.exists(temp_file):
        os.remove(temp_file)

方法二:使用fileinput模块的原地编辑

Python的fileinput模块支持原地修改文件,内部会自动创建临时文件处理,代码更简洁:

import fileinput

word = "five"

try:
    # inplace=True表示原地修改,backup='.bak'会生成原文件的备份
    with fileinput.input("test.txt", inplace=True, backup='.bak') as f:
        for line in f:
            if word not in line:
                print(line, end='')  # print默认加换行,这里用end=''保留原行的换行符
except FileNotFoundError:
    print("文件不存在!")

注意事项

  • 方法一中,直接读写同一个文件会导致原文件内容被清空,所以必须用临时文件中转。os.replace()比os.rename()更安全,能跨平台处理文件替换。
  • 方法二中,backup='.bak'会保留原文件的备份,避免修改出错丢失数据;如果不需要备份可以去掉这个参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 01:55:18