How to remove a line in txt file in python

Question:

Good night, I'm having problems removing a line from a txt file, the code's delete function is responsible for removing a user, however when 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!")

Answer:

Your problem is here while posi in loginAndPass: . You delete the file in users = open("users.txt", 'w') and the code in while will never run, because you are looking for an 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()
Scroll to Top
AllEscort