How to remove a line in txt file in python

0

Good night, I'm having problems removing a line from a txt file, the delete function of the code is responsible for removing a user, however when I try to remove the whole file it 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!")
    
asked by anonymous 12.11.2018 / 02:19

1 answer

0

Your problem is in this here while posi in loginAndPass: . You delete the file in users = open("users.txt", 'w') and the code in while will never be executed, because you are looking for int in 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()
    
12.11.2018 / 13:43