python - 如何使用 python 删除文本文件中的多行?

标签 python

我正在通过编写电话簿程序来练习我的 Python 技能。我可以搜索和添加条目,但删除条目时遇到很多麻烦。

我试图找到与我的搜索相匹配的行,然后删除它以及接下来的 4 行。我这里有一个函数要删除:

def delete():
    del_name = raw_input("What is the first name of the person you would like to delete? ")
    with open("phonebook.txt", "r+") as f:
            deletelines = f.readlines()
            for i, line in enumerate(deletelines):
                if del_name in line:
                    for l in deletelines[i+1:i+4]:
                        f.write(l)

这是行不通的。

如何从这样的文本文件中删除多个条目?

最佳答案

回答您的直接问题:您可以使用 fileinput 轻松地就地更改文本文件:

import fileinput
file = fileinput.input('phonebook.txt', inplace=True)

for line in file:
     if word_to_find in line:
         for _ in range(4): # skip this line and next 4 lines
             next(file, None)
     else:
         print line,

为了避免将整个文件读入内存,这会在后台为您处理一些事情 - 它将您的原始文件移动到临时文件,写入新文件,然后删除临时文件。

可能更好的答案:看起来您推出了一个自制的序列化解决方案。考虑使用内置库,如 csvjsonshelve,甚至 sqlite3 将数据保存在一种更易于使用的格式。

关于python - 如何使用 python 删除文本文件中的多行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25815373/

相关文章:

python - Scrapy:通过管道从数据库获取Start_Urls

python - 当我们递归使用 yield 时,我们会创建 n 个迭代器吗?

尽管出现 UnicodeDecodeError,Python 3 itertools.islice 仍继续

Python - 解析 Json 和 XML 哪个更快?

python - 如何获取Opennebula XML-RPC api需要的参数

python - django prefetch_related 是否应该与 GenericRelation 一起使用

python - 格式错误的 Lambda 代理响应 : string indices must be integers

python - findall 内的正则表达式 vs 计数内的正则表达式

python - 生成要导入到 pandas df 的元组列表

Python 分析方法