我正在通过编写电话簿程序来练习我的 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,
为了避免将整个文件读入内存,这会在后台为您处理一些事情 - 它将您的原始文件移动到临时文件,写入新文件,然后删除临时文件。
可能更好的答案:看起来您推出了一个自制的序列化解决方案。考虑使用内置库,如 csv
、json
、shelve
,甚至 sqlite3
将数据保存在一种更易于使用的格式。
关于python - 如何使用 python 删除文本文件中的多行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25815373/