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

Question:

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

Asked By: Spaghetti

||

Answers:

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.

Answered By: Ethan Kinney

writeLines does not have any return value and therefore would have no value in using in a if statement 🙂

https://python-reference.readthedocs.io/en/latest/docs/file/writelines.html

Answered By: a_confused_student
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.