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

如何在文本文件中删除指定行?Python笑话程序删除功能异常求助

笑话程序删除功能修复方案

问题核心

你的删除功能会清空整个文件,本质是写入文件时仅对匹配到的行写空字符串,其余行完全没写入文件,导致文件被覆盖为空。另外readlines()读取的行自带末尾换行符\n,和jokes列表里的内容可能不匹配,就算想删也可能出现判断错误。

修复后的代码

def remove_joke():
    for i in range(len(jokes)):
        print(f"{i}\t{jokes[i]}")
    
    remove_index = int(input("Enter the number of the joke you want to remove:\t"))
    target_joke = jokes[remove_index]

    with open("jokes.txt", "r") as f:
        lines = f.readlines()
    
    # 统一处理换行符,避免匹配失败
    target_joke_with_newline = target_joke + '\n' if not target_joke.endswith('\n') else target_joke

    with open("jokes.txt", "w") as f:
        for line in lines:
            # 跳过目标行,其他行正常写入
            if line != target_joke_with_newline:
                f.write(line)
    
    jokes.pop(remove_index)  # 指定索引删除,比remove更可靠

关键改动说明

  • 保留有效行写入:遍历文件行时,只跳过要删除的条目,其余行正常写入,不会清空整个文件。
  • 匹配换行符:解决readlines()带换行符和列表内容不一致的问题,确保能精准定位要删除的行。
  • 精准删除列表元素:用pop(remove_index)直接删除指定索引的笑话,避免remove()在有重复笑话时删错的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 13:00:49