-4

I wrote a code to create a user and login but the created user will be in memory only till the program is running and when the program closes then the user gets destroyed. Now if I decide to store the username and password to a file, then how can I do so in the below python code.I just want to store it to a file not to read or compare it yet. And I just started learning Python so don't know anything advance or any tricky terms.

Edit: I am unable to write the username and password to the file.

users = {}
status = ""

f = open('E:\\login_try2.txt','w')

def displayMenu():
    status = input("Are you registered user? y/n/q ")
    if status == "y":
        oldUser()
    elif status == "n":
        newUser()
    elif status == "q":
        exitCode()

def exitCode():
    exit()

def newUser():
    username = input("Enter username: ")     
    f.write(username)

    if username in users:
        print("\nUsername already exists!\n")
    else:
        password = input("Create Password: ")
        users[username] = password
        f.write(password)
        print("\nUser created\n")

def oldUser():
    login = input("Enter username: ")
    passw = input("Enter password: ")

    if login in users and users[login] == passw:
        print("\nLogin Successful!\n")
    else:
        print("\nUser doesnt exist or wrong password!\n")

while status != "q":
    displayMenu()

f.close()
9
  • What's the problem you are seeing with your code? A problem statement and a code dump is nice, but it doesn't show us where we can help clarify a specific issue. Commented Jul 17, 2018 at 16:57
  • I am unable to write the username and password to the file. Commented Jul 17, 2018 at 16:59
  • Possible duplicate of stackoverflow.com/questions/1047318/… Commented Jul 17, 2018 at 17:02
  • Getting any errors? Commented Jul 17, 2018 at 17:03
  • i am not getting any errors and the program is running fine Commented Jul 17, 2018 at 17:03

2 Answers 2

1

The problem is that your f.close() statement is only executed after exiting the application, so the data is not reliably flushed to the file.

Probably the easiest solution is to move f.close() to after f.write(password) in the newUser function.

Sign up to request clarification or add additional context in comments.

Comments

0

The answer was quite simple. The f.close() was not getting called due to which the program was not able to store data in the file. So I added f.close() in the def exitCode():

def exitCode():
    f.close()
    exit()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.