Gaurav
Gaurav

Reputation: 333

fault in readline() or condition

I am getting a problem in my code. I created a program which creates an account, saves username and password in a .txt file. Then asks for login and it checks whether the username and password is corrent or not. But everytime the else condition is executing. And i am getting output "You don' have any account". Please help. Thanks in advance.

# MyProgram: Account Verification 

print "\ncreate account:\n"
f = open("data.txt",'w+')

def create():
    user_name = raw_input("Enter username >> ")
    password = raw_input("Enter password >> ")
    confirm = raw_input("Enter password to confirm >> ")
    if password == confirm:
        f.write(user_name+"\n"+password)
        f.close()
        print "Account created"
    else:
        print "\nPassword not matched\n\n Enter details again:\n"
        create()

create() 

new = open("data.txt")
un = new.readline()
pw = new.readline()

new.close()

def login():
    print "\nLogin:\n"
    name = raw_input("Enter username >> ")
    if name == un:
        pas = raw_input("Enter password >> ")
        if pas == pw:
            print "Welcome!"
        else:
            print "Wrong password"
            login()                
    else:
        print "You don't have any account" 

login()     

Upvotes: 0

Views: 37

Answers (1)

Kevin
Kevin

Reputation: 76254

readline includes the newline character at the end of the line, so you're probably comparing e.g. "hunter2\n" to "hunter2". Try stripping the whitespace off first.

un = new.readline().strip()
pw = new.readline().strip()

Alternatively, it may be preferable to store/retrieve your usernames and passwords in some way other than writing strings to and reading strings from a plain text file. For very lightweight applications, simple serialization like the pickle or json libraries might suffice; but anything really serious would benefit from a proper database. With any of these, you probably won't need to worry about the behavior of readline() at all.

Upvotes: 2

Related Questions