Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading