I want to delete a row of text from a text file. This is my code:
with open("contactbook.txt","r") as file:
for num, line in enumerate(file, 1):
if args.name in line:
filedata = file.read()
filedata = filedata.replace(line, " ")
with open('contactbook.txt', 'w') as file:
file.write(filedata)
The texts are arranged like this:
Name:Hello Phone number: 9 Address: 9 E-mail: 9
Name:Hi Phone number: 8 Address: 8 E-mail: 8
NOTE: The actual file contains a lot of rows, the one above just shows how it looks like.
So for example, if I want to delete the row containing "Hi", I only want the following to remain.
Name:Hello Phone number: 9 Address: 9 E-mail: 9
NOTE: The user input is only "Hi" but it will delete the entire row where it is found.
My code works sometimes but there are times it ends up deleting everything (the entire content of the text file), what am I doing wrong and what's a better way to do this?