def Delete_con():
contact_to_delete= input("choose name to delete from contact")
to_Delete=list(contact_to_delete)
with open("phonebook1.txt", "r+") as file:
content = file.read()
for line in content:
if not any(line in line for line in to_Delete):
content.write(line)
我得到零错误。但该行未删除。此功能询问用户他或她想要从文本文件中删除的名称。
答案 0 :(得分:0)
这应该有所帮助。
def Delete_con():
contact_to_delete= input("choose name to delete from contact")
contact_to_delete = contact_to_delete.lower() #Convert input to lower case
with open("phonebook1.txt", "r") as file:
content = file.readlines() #Read lines from text
content = [line for line in content if contact_to_delete not in line.lower()] #Check if user input is in line
with open("phonebook1.txt", "w") as file: #Write back content to text
file.writelines(content)
答案 1 :(得分:0)
假设:
我会做这样的事情:
import os
from tempfile import NamedTemporaryFile
def delete_contact():
contact_name = input('Choose name to delete: ')
# You probably want to pass path in as an argument
path = 'phonebook1.txt'
base_dir = os.path.dirname(path)
with open(path) as phonebook, \
NamedTemporaryFile(mode='w+', dir=base_dir, delete=False) as tmp:
for line in phonebook:
# rsplit instead of split supports names containing ':'
# if numbers can also contain ':' you need something smarter
name, number = line.rsplit(':', 1)
if name != contact_name:
tmp.write(line)
os.replace(tmp.name, path)
使用这样的临时文件意味着如果在处理文件时出现问题,您没有留下半写的电话簿,您仍然可以保持原始文件不变。你也没有用这种方法将整个文件读入内存。
os.replace()
仅适用于Python 3.3+,如果您使用的是旧版本,只要您不使用Windows,就可以使用os.rename()
。
Here's the tempfile documentation。在这种情况下,您可以将NamedTemporaryFile(mode='w+', dir=base_dir, delete=False)
视为open('tmpfile.txt', mode='w+')
之类的内容。 NamedTemporaryFile使您不必为临时文件找到唯一的名称(这样您就不会覆盖现有文件)。 dir
参数在与phonebook1.txt
相同的目录中创建临时文件,这是一个好主意,因为os.replace()
在跨两个不同的文件系统操作时可能会失败。