pythonfileif-statementoutput

Can an Python writeline() be used in an IF statement?


I'm trying to make a simple password manager. This is my function for adding passwords: ]

def add():
    
    cont=input("You would like to add a password? (y/n)")
    if cont.capitalize() == "Y":
        passwords = open("Passwords.txt","a")
        username_ = input("What is the username?")
        password_ = input("What is the password?")
        L = [username_, " ", password_]
        if(passwords.writelines(L)):
            print("Written successfully!")
            print("Quiting to option select...\n")
            main()
        else:
            print("Hmm. That didn't seem to work.")
            main()
    else:
        print("Quiting to option select...\n")
        main()
    

I always receive "Hmm. That didn't seem to work." when I try to add new passwords. The intended functionality of this is so that if a password is written, then it will say written successfully. Written in this case means appended, hence the 'a' in the opening of the file.

I tried using sudo to run it, but that wasn't the issue. I tried changing the append, to just 'w'.


Solution

  • You could use try-except method.

    try:
        passwords.writelines(L)
    except:
        print("Hmm. That didn't seem to work")
    else:
        print("Written successfully!")
        print("Quiting to option select...\n")
    

    Also, you could try using check_output() but I have no idea if writelines would work with that.