这是一个python文件,应该像电话簿一样这个文件名为test。txt它应该创建,保存,追加,搜索和删除联系人但是删除部分删除所有字符串而不是特定字符串(执行时其余代码是ok的删除部分是代码的最后一部分)
#inputing contacts
filename ="exam.txt"
n = int(input("enter the number of contacts you would like to saven"))
file = open(filename, "a")
for i in range(n):
cont = (input("enter name and phone number respectively:n"))
file.write(cont + "n")
file.close
#searching for contacts
word = input("insert the name you would like to search forn")
with open("exam.txt", "r") as file:
for line_number, line in enumerate(file, start=1):
if word in line:
print(f"Word '{word}' found on line {line_number}")
break
print("Search completed.")
#deleting contacts
# deleting a string/contact
try:
with open('exam.txt', 'r') as fr:
lines = fr.readlines()
with open('exam.txt', 'w') as fw:
for line in lines:
# strip() is used to remove 'n'
# present at the end of each line
if line.strip('n') != input("input the contact you would like to delete:"):
fw.write(line)
break
print("Deleted")
except:
print("Oops! something error")
一些改进和更正(针对您的具体问题,参见第6项)。
- 您首先要求用户输入他们希望输入的联系人数量。如果他们有一个很长的名单呢?你是在强迫他们手动计算名单上的名字数量。最好是继续输入,直到输入空行。没有人需要计算任何东西。
- 您有
file.close
。这只是引用一个函数而不调用它。你需要file.close()
。更好的是使用上下文管理器,它将自动为您发出关闭(我看到现在您已经做了这个更改)。 - 你已经定义了
filename="exam.txt"
,这很好(虽然使用由所有大写字母组成的变量名称更常用于定义常量)。但是稍后当你在删除联系人代码时,你需要硬编码"test .txt";再一次。如果你以后决定使用不同的文件名,你现在必须在两个地方修改它。 - 在联系人删除代码中,您正在为联系人文件的每一行请求联系人的名称。那不可能是你真正想要的,对吧?
- 在删除代码中,您同时打开了文件两次,一次用于读取,一次用于写入。这不是必需的,而且容易混淆。
- 您需要写出
lines
变量中的每一行,即使在您找到要删除的联系人之后。 - 不使用
file.write(line + 'n')
,您可以使用print(line, file=file)
,换行符将自动添加。 一个更好的变量名选择使代码更清晰。
FILENAME = "exam.txt"
def get_contact():
while True:
contact = input("Enter the contact name: ").strip()
if contact != '':
return contact
#inputing contacts
print('Enter the name followed by a phone number for each contact you want to enter.')
print('When through, enter an empty line.')
print()
with open(FILENAME, "a") as file:
while True:
entry = input('Enter next name and phone numer: ').strip()
if entry == '':
break
print(entry, file=file)
#searching for contacts
contact = get_contact()
with open(FILENAME, "r") as file:
for line_number, entry in enumerate(file, start=1):
entry = entry.strip()
if entry.startswith(contact):
print(f"Contact '{contact}' found on line {line_number}: {entry}")
# Uncomment out the following if you only want to list the first match:
#break
print("Search completed.")
#deleting contacts
# deleting a string/contact
contact = get_contact()
try:
with open(FILENAME, 'r') as file:
entries = file.readlines()
found_contact = False
with open(FILENAME, 'w') as file:
for entry in entries:
# No need to strip off the 'n' at the end:
if not entry.startswith(contact):
print(entry, file=file, end='') # There is already a newline
# or file.write(entry)
else:
found_contact = True
if found_contact:
print(f"Contact `{contact}` deleted.")
else:
print(f"Could not find contact '{contact}'.")
except:
print("Oops! something error")
我对Python的了解非常基础,但是我认为只要使用open
功能,写入"w"
模式。我的解决方案是首先将行读入列表,删除用户输入指定的行,然后使用该列表重新写入文件。我的文件格式是:
迈克尔·穆勒123nPeter Gabriel 456n…
user_input = input("Please enter a name:")
file = open("pbook.txt")
file_contents = file.readlines()
file.close()
for index in range(int(len(file_contents) - 1), -1, -1):
line = file_contents[index].strip()
if line.find(user_input) != -1:
print(f"{line} was removed from the phonebook.")
file_contents.pop(index)
print(file_contents)
file = open("pbook.txt", "w")
file.writelines(file_contents)
file.close()
试试这个delete函数。
# deleting a string/contact
with open('exam.txt', 'r') as fr:
# Get all the line/contacts from the file
lines = fr.readlines()
# Get the string to be deleted.
delete = input("insert the name you would like to delete: n")
if delete != "" :
with open('exam.txt', 'w') as fw:
for line in lines:
# This will put back all lines that don't start with the
provided string.
if not (line.startswith(delete)):
fw.write(line)
print("Deleted")