如何使用Python中的delete函数删除txt文件中的指示行



我是一名学生,有一项任务是创建一个使用oop、函数、txt文件和导入操作系统的联系人簿。我刚刚决定创建一本使用函数和txt文件的书。和我遇到了一些删除txt文件中指示行(记录(的问题。我尝试了很多不同的方法。结果:删除文件中的所有信息或最后一行,或者简单地读取文件,仅此而已。我所需要的只是根据指示的输入(单词/名称(删除一条记录。我的导师教我使用一个del函数:

if each_contact.name==name:
del list_contacts[i]

但是我根本不知道如何使用这个函数。逻辑应该是什么?我的代码是这样的:

def del_contact_name():
## It should delete the required line as per name if txt file  
del_name=input('Enter first name for delete  this contact record:  ')
del_name=del_name.title()
with open(file_name, "r") as f:
file_delete = f.readlines()
with open(file_name, "w") as f:
for line in file_delete:
if line != del_name:
f.write(line)
print("Your Required Contact Record is deleted:", end=" ")
break

如果我写了3行记录,这只是删除最后一行(它有效,但我需要另一个结果(。如果我做一个记录,它不会删除,而是读取行。完整的工作看起来像这样:

file_name = "phonebook.txt"
filerec = open(file_name, "a+")
filerec.close

def show_main_menu():
## General menu 
print("n   Phone Book     n"+
"    my task and projects         n"+
"=================================n"+
"Enter 1,2,3,4 or 5:n"+
" 1 To Display Contacts Recordsn" +
" 2 To Add a New Contact Recordn"+
" 3 To Search Contactsn"+
" 4 To Delete Contactsn"+
" 5 To Quitn=========================")
choice = input("Enter your choice: ")
if choice == "1":
filerec = open(file_name, "r+")
file_contents = filerec.read()
if len(file_contents) == 0:
print("Phone Book is Empty")
else:
print (file_contents)
filerec.close
entry = input("Press Enter to continue ...")
show_main_menu()
elif choice == "2":
enter_contact_record()
entry = input("Press Enter to continue ...")
show_main_menu()
elif choice == "3":
search_contact_record()
entry = input("Press Enter to continue ...")
show_main_menu()
elif choice=='4':
del_contact_name()
entry=input("Press Enter to continue ...")
show_main_menu()
elif choice== "5":
print("Thanks for using Phone Book Programm ")
else:
print("Wrong choice, Please Enter [1 to 5]n")
entry = input("Press Enter to continue ...")
show_main_menu()

def search_contact_record():
##' This function is used to searches a specific contact record 
search_name = input("Enter First name for Searching contact record: ")
search_name = search_name.title()
filerec = open(file_name, "r+")
file_contents = filerec.readlines()

found = False   
for line in file_contents:
if search_name in line:
print("Your Searched Contact Record is:", end=" ")
print (line)
found=True
break
if  found == False:
print("There's no contact Record in Phone Book with name = " + search_name )
def enter_contact_record():
##  It  collects contact info firstname, last name, notes and phone

first = input('Enter First Name: ')
first = first.title()
last = input('Enter Last Name: ')
last = last.title()
phone = input('Enter Phone number: ')
notes = input('Enter notes: ')
contact = ("[" + first + " " + last + ", " + phone + ", " + notes +  "]n")
filerec = open(file_name, "a")
filerec.write(contact)
print( "This contactn " + contact + "has been added successfully!")

def del_contact_name():
## It should delete the required line as per name in txt file  
del_name=input('Enter first name for delete  this contact record:  ')
del_name=del_name.title()
with open(file_name, "r") as f:
file_delete = f.readlines()
with open(file_name, "w") as f:
for line in file_delete:
if line != del_name:
f.write(line)
print("Your Required Contact Record is deleted:", end=" ")
break
show_main_menu()
file_name = "phonebook.txt"  
def show_main_menu():
## General menu 
print("n   Phone Book     n"+
"    my task and projects         n"+
"=================================n"+
"Enter 1,2,3,4 or 5:n"+
" 1 To Display Contacts Recordsn" +
" 2 To Add a New Contact Recordn"+
" 3 To Search Contactsn"+
" 4 To Delete Contactsn"+
" 5 To Quitn=========================")
choice = input("Enter your choice: ")
if choice == "1":
show_file()
entry = input("Press Enter to continue ...")
show_main_menu()
elif choice == "2":
add_file()
entry = input("Press Enter to continue ...")
show_main_menu()
elif choice == "3":
search_file()
entry = input("Press Enter to continue ...")
show_main_menu()
elif choice=='4':
dell_file()
entry=input("Press Enter to continue ...")
show_main_menu()
elif choice== "5":
print("Thanks for using Phone Book Programm ")
else:
print("Wrong choice, Please Enter [1 to 5]n")
entry = input("Press Enter to continue ...")
show_main_menu()

def initials():
first = input('Enter First Name: ')
first = first.title()
last = input('Enter Last Name: ')
last = last.title()
phone = input('Enter Phone number: ')
notes = input('Enter notes: ')
contact = ("[" + first + " " + last + ", " + phone + ", " + notes +  "]n")
return contact
def show_file():
#show file
filerec = open(file_name, "r+")
file_contents = filerec.read()
if len(file_contents) == 0:
print("Phone Book is Empty")
else:
print (file_contents)
filerec.close()
def add_file():
#add text to a file
with open(file_name, 'a') as f:
f.write(initials())
f.close()
def search_file():
##' This function is used to searches a specific contact record 
search_name = input("Enter First name for Searching contact record: ")
# If you enter not a name, but a sign that is in the record, then he will find it
search_name = search_name.title()
filerec = open(file_name, "r+")
file_contents = filerec.readlines()
found = True
for line in file_contents:
if search_name in line:
print("Your Searched Contact Record is:", end=' ')
print (line)
found=False
break  
if found:
print("There's no contact Record in Phone Book with name = " + search_name )
filerec.close()
def dell_file():
## It should delete the required line as per name in txt file  
del_name=input('Enter first name for delete  this contact record:  ')
del_name=del_name.title()
count_str = 0 
no_string = True
with open(file_name, "r+") as file:
lines = file.readlines()
for i in lines:   
count_str +=1       
if del_name in i:
no_string = False
del lines[count_str-1]   
break
if no_string:
print('No line')
with open(file_name, "w") as file:
file.writelines(lines)                
file.close()
show_main_menu()

现在删除操作正在进行。

相关内容

最新更新