Python Forum
Login and register code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Login and register code
#1
I have to make code that lets you create an account or log in and it must save the accounts to a text file, I have done the create account but its very badly done and don't have a clue how to do the login as I don't understand read files, thank you for any help




(Login code I wrote)
def reg():
    uname=input("Please a username: ")
    pword=input("Please a a passwrd: ")
    f = open("UNPW.txt", "a")
    f.write("\nUsername:"+uname)
    f.write("\nPasswod:"+pword)
    f.write("\n----------------------------")
Reply
#2
Firstly, here's your definition of ref with a minor correct to the text your write to file (you mistyped Password):

def reg():
    uname = input("Please enter a username: ")
    pword = input("Please enter a password: ")
    with open("UNPW.txt", "a") as f:
        f.write("\nUsername:"+uname)
        f.write("\nPassword:"+pword)
The with open() saves you having to remember to close a file. Otherwise it is the same as you had.

Here's a new example function called login that returns True if it finds a matching username and password in the file. Otherwise, it returns False.

def login():
    uname = input("Please enter your username: ").lower()
    pword = input("Please enter your password: ")
    found = False
    with open("UNPW.txt", "r") as f:
        for line in f:
            if line.strip().startswith('Username:'):
                if line.strip().lower().endswith(uname):
                    line = next(f)
                    if line.strip().startswith('Password:'):
                        if line.strip().endswith(pword):
                            found = True
                    break
    return found
So, you use a for loop to read a line at a time from the file. The strip() modifies the string in the expression to ignore leading and trailing whitespace characters. next(f) reads the next line in the file before the next iteration of the for loop. We are assuming that the User line is followed by a Password line.

To test it, firstly, lets called reg() three times to add some usernames and passwords. Then lets see if we can find a match.

reg()
reg()
reg()
security_passed = login()
print(security_passed)
You have more work to do including adding some more error checking, allowing more than one attempt at login perhaps, disguising the passwords rather than saving them as plain text (look up hashing of passwords).
I am trying to help you, really, even if it doesn't always seem that way
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Login/register system. Exploiterz 5 3,893 May-15-2018, 05:32 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020