Python – Remove string from TXT file

  data-structures, python, python-2.7, python-3.x

I tried to solve it in many different ways but I never get it to work properly.
My problem is that I have a list of users that it is a TXT file and I want to remove one of the users.

So, the closes that I got is this:

elif name.lower() == 'remove':
        rem = input("Insert user name to remove n ...")
        with open('names.txt', 'r+') as f:
            f.delete(f.find(rem))

The text document is something like this:

Alex
Sarah
Mathew
Sophie

Only one string (user) every line.

thank you very much.

Full code for better understanding:

snames = list()
f_n = (open('names.txt')).read()
print("Welcome to NAME.app")
#try:
while True:
    name = input("n - Insert name to logg in n - ADD to save new user n - LIST to see saved users n - REMOVE to delete a user n ...")
    if name.lower() == "add":
        n_input = input("Name:")
        with open('names.txt', 'a') as f:
            f.write(n_input + 'n')
            f.close()
        continue

    elif name.lower() == "list":
        with open('names.txt') as f:
            print(f.read().splitlines())

    elif name in f_n:
        print("Logged as", name.upper())
        nxt = input('Welcome, press enter to continue n')
        if nxt == '':
            break

    elif name.lower() == 'remove':
        rem = input("Insert user name to remove n ...")
        with open('names.txt', 'r+') as f:
            f.delete(f.find(rem))

    elif name.lower() == "exit":
        exit()

Source: Python Questions

LEAVE A COMMENT