This is a python file that's supposed to act like a phone book the file is called exam.txt its supposed to create, save, append, search and delete contacts but the delete part deletes all the strings instead of specific strings (the rest of the code is ok when executed the deleting part is the last part of the code)
#inputing contacts
filename ="exam.txt"
n = int(input("enter the number of contacts you would like to save\n"))
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 for\n")
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")
A few improvements and corrections (for your specific issue, see Item 6).
file.close
. That just references a function without calling it. You need file.close()
. Better yet is to use a context manager that will automatically issue the close for you (I see now you have already made this change).filename="exam.txt"
That's good (although using a variable name consisting of all capital letters is moreusual for defining constants). But later when you are in the contact-deletion code you hardcode "exam.txt" again. If you decide later to use a different file name you now have to change it in two places.lines
variable, even after you found the contact to delete.file.write(line + '\n')
, you can do print(line, file=file)
and the newline will be added automatically.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")