How to remove a line in python txt file

Asked

Viewed 4,431 times

3

Good evening, I am having problems while removing a line from a txt file, the deleting function of the code is responsible for removing a user, however while trying to remove the entire file is deleted.

def deleta():

    usuario = input("\nUsuário: ") + "\n"
    senha = input("Senha: ")
    confirma = input("Confirma a exclusão de "+usuario+"? \ns/n: ")
    confirma.lower()

    if confirma == 's' or 'sim':
        with open("users.txt", 'r') as users:
            loginAndPass = users.readlines()
            # Proucura pelo login
            if usuario in loginAndPass:
                posi = loginAndPass.index(usuario)
                # autentica
                if posi % 2 != 0:
                    if testSHA512(senha, loginAndPass[int(posi) + 1].replace('\n', '')):
                        users = open("users.txt", 'w')
                        while posi in loginAndPass:
                            loginAndPass.remove(posi)
                            users.writelines(loginAndPass)
                            users.close()
                        print("\nUsuario removido\n")
                    else:
                        print("\nUsuário ou Senha inválidos\n")
                else:
                    print("\nUsuário ou Senha inválidos\n")
            else:
                print("\nUsuário ou Senha inválidos\n")
    elif confirma == 'n' or 'nao':
        print("passou")
    else:
        print("Opção inválida\nPrograma finalizado!")
  • 2

    The line confirma.lower() is useless because str.lower() returns a copy of the converted string to lowercase and you’re not saving the result. What you want to do seems to be confirma = confirma.lower(). And the line if confirma == 's' or 'sim': doesn’t do what you think it does, the right thing would be if confirma == 's' or confirma == 'sim': or if confirma in ('s', 'sim'):.

  • Thanks for the tip, I made the changes nescessarias.

  • One more tip, you opened the file for reading on this line: open("users.txt", 'r') as users but is trying to record in users.writelines(loginAndPass)

1 answer

1

Your problem is in this while posi in loginAndPass:. You delete the file in users = open("users.txt", 'w') and the code in the while will never run because you are looking for a int on a list that only has strings.

If your password is on the next line use this:

# remove o usuario
loginAndPass.pop(posi)
# remove a senha
loginAndPass.pop(posi)
users = open("users.txt", 'w')
users.writelines(loginAndPass)
users.close()
  • Thank you very much, I solved with your tip, sorry for the triviality, but I’m new in python and I don’t know many functions, now is to solve the problem of salting the password.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.