Home > Mobile >  How can I remove a string from a txt file?
How can I remove a string from a txt file?

Time:11-20

I am trying to create a contact info txt file with python

what_you_want = input("Do you want to add or remove (if add write add), (if remove write remove): ")

if what_you_want == "remove":
    what_you_want_remove = input("What contact number you want to remove: ")
    with open("All Contact.txt", "r") as f:
        contact_info = f.readlines()
    if what_you_want_remove in contact_info:
        with open("All Contact.txt", "a") as f:
            if what_you_want_remove in contact_info:
                new_contact_info = contact_info.replace(what_you_want_remove, "")
            f.write(new_contact_info)

I couldn't find a way to directly remove something from a txt file so I want to put it into a list and then write it back to txt file but when I try to use remove command it doesn't work.

I want to ask if there is a way to remove something from a text file directly.

CodePudding user response:

You can read the file into a string or list, remove the substring, and write back to the file. For instance,

with open("file.txt", "w") as f:
    string = f.readlines()
    string = string.replace(substring, "")
    f.write(string)

If substring does not exist in file.txt, the replace function will not perform any action. If you want the replacement to be case-insensitive, you could try lowering the entire buffer as well as the subtring via string = string.lower() and substring = substring.lower().

CodePudding user response:

Use del to delete that entry. Then overwrite the original file, making it one line shorter.

if what_you_want_remove in contact_info:
    i = contact_info.index(what_you_want_remove)
    del contact_info[i]

    with open("All Contact.txt", "w") as fout:
        fout.write("\n".join(contact_info)
        fout.write("\n")
  • Related