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

如何在Python中删除文本文件指定行之后的所有内容

删除文本文件中指定行之后的所有行的解决方案

原代码的问题分析

  • readlines()返回的是每行组成的列表,re.search的第二个参数要求是字符串,直接传列表会触发类型错误。
  • 正则表达式中(.|\n)的写法不够简洁,且未启用跨行匹配模式,无法正确捕获换行后的内容。

解决方案1:按行遍历(直观易维护)

直接遍历文件的每一行,找到目标行的位置后截断内容:

with open("file1.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()

cut_index = None
for idx, line in enumerate(lines):
    # 匹配目标行(可根据需求调整判断逻辑,比如精确匹配或包含关键词)
    if "Here begins the" in line.strip():
        cut_index = idx
        break

# 若找到目标行,保留该行之前的所有内容;未找到则保留原文件
if cut_index is not None:
    lines = lines[:cut_index]

with open("file1.txt", "w", encoding="utf-8") as f:
    f.writelines(lines)

解决方案2:正则表达式处理(适合复杂匹配场景)

将文件内容读为完整字符串,用正则捕获目标行之前的所有内容:

import re

with open("file1.txt", "r", encoding="utf-8") as f:
    content = f.read()

# 正向预查匹配目标字符串,非贪婪捕获之前的所有内容(含换行)
match_result = re.match(r"(.*?)(?=Here begins the)", content, re.DOTALL)
if match_result:
    new_content = match_result.group(1)
    with open("file1.txt", "w", encoding="utf-8") as f:
        f.write(new_content)

原代码修正版

针对你最初的思路,调整代码如下(修正参数类型和正则模式):

import re  
with open("file1.txt", "r", encoding="utf-8") as f:  
    content = f.read()  # 读取为完整字符串而非列表

# 启用re.DOTALL让.匹配换行符,匹配目标行及之后的所有内容
found_match = re.search(r'Here begins the.*', content, re.DOTALL)  
if found_match:
    # 截取匹配位置之前的内容
    new_content = content[:found_match.start()]  
    with open("file1.txt", "w", encoding="utf-8") as f:  
        f.write(new_content)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 19:08:32