简体   繁体   English

python读/写文件登录脚本

[英]python read/write to file login script

I was wondering if anyone would help.我想知道是否有人会帮忙。 I am new to python.我是python的新手。 I am trying to create a basic login script for a game, that will write a username and password to a text file.我正在尝试为游戏创建一个基本的登录脚本,它将用户名和密码写入文本文件。 When logging in, it will read from that text file and compare the entry made by the user.登录时,它将从该文本文件中读取并比较用户所做的输入。 The code is below:代码如下:

def Register():
    print("Hello! You need to register an account before you can begin")
    username = input("Please enter a username: ")
    password = input("Now please enter a password: ")
    file = open("Login.txt","a")
    file.write (username)
    file.write (",")
    file.write (password)
    file.write("\n")
    file.close()
    print ("Your login details have been saved. ")
    print("You will now need to login")
    Login() 

def Login():
    print("Please enter your details to log in")
    username1 = input("Please enter your username: ")
    password1 = input("Please enter your password: ")

    file = open("Login.txt","r")

    for row in file:
        field = row.split(",")
        username = field[0]
        password = field[1]
        lastchar = len(password)-1
        password = password[0:lastchar]
        print(username,password)

        if username1 == username and password1 == password:
            print("Hello",username)

        else:
            print("incorrect")

#file.close()


 user=input("Are you already a user? ")

 if user == "Yes":
     Login()

 elif user =="No":
     Register()

 print("Welcome to our game")

I have entered the second user who is stored in the text file, It seems to be working but it checks my first entry and says its incorrect and then loops to the second entry.我已经输入了存储在文本文件中的第二个用户,它似乎正在工作,但它检查了我的第一个条目并说它不正确,然后循环到第二个条目。 This is the output I keep getting:这是我不断得到的输出:

Are you already a user? Yes
Please enter your details to log in
Please enter your username: jen
Please enter your password: ben
tess bess
incorrect
jen ben
Hello jen
Welcome to the dice game
>>> 

Does anyone have an idea on how to only display the entry you have entered?有没有人知道如何只显示您输入的条目?

Thanks谢谢

Like Sharku said, put the print(username,password) in your if below.就像 Sharku 说的,把打印(用户名,密码)放在你的 if 下面。 Also writting clearly the name and password of the user after he typed it isn"t really a smart moove, delete it and just let your message when a user is logging in !在用户输入后写清楚用户名和密码也不是一个明智的举动,删除它并在用户登录时让您的消息!

for row in file:
    field = row.split(",")
    username = field[0]
    password = field[1]
    lastchar = len(password)-1
    password = password[0:lastchar]

    if username1 == username and password1 == password:
        print("Hello",username)

    else:
        print("incorrect")

As said by sytech, you could use the break and else clauses of the for loop:正如 sytech 所说,您可以使用 for 循环的breakelse子句:

for row in file:
    field = row.split(",")
    username = field[0]
    password = field[1]
    lastchar = len(password)-1
    password = password[0:lastchar]

    if username1 == username and password1 == password:
        print("Hello",username)
        break
else:
    print("incorrect")

Your 'for loop' will loop through each entry in your file, that means for each entry in the file your for loop prints the entry due to this line:您的“for 循环”将遍历文件中的每个条目,这意味着对于文件中的每个条目,您的 for 循环会打印由于此行而导致的条目:

    print(username,password)

If you don't want it to print all values in the file remove this line of code.如果您不希望它打印文件中的所有值,请删除这行代码。 Adding a 'break' to your if statement, as suggested by others, will mean that as soon as your loop has found the entry that matches the one entered by the user it will leave the loop and not continue going through all values unnecessarily.正如其他人所建议的那样,在您的 if 语句中添加一个“中断”将意味着一旦您的循环找到与用户输入的条目匹配的条目,它将离开循环并且不会继续不必要地遍历所有值。

You could do something like this:你可以这样做:

    if username1 == username and password1 == password:
        print("Hello",username)
        break

    else:
        continue

This means that when a user input doesn't match an entry in the file the loop will just continue till it finds a match.这意味着当用户输入与文件中的条目不匹配时,循环将继续直到找到匹配项。 However, your code doesn't take into consideration if a user doesn't exist.但是,如果用户不存在,您的代码不会考虑在内。

import os.path

if not os.path.exists('register.txt'):
    file = open('register.txt', 'w')
    file.close()


def register():
    username = input('Enter username: ')
    if username in open('register.txt', 'r').read():
        print('Username already exists')
        exit()
    password = input('Enter password: ')
    c_password = input('Enter confirm password: ')
    if password != c_password:
        print('Sorry password not match')
        exit()
    handle = open('register.txt', 'a')
    handle.write(username)
    handle.write(' ')
    handle.write(password)
    handle.write('\n')
    handle.close()
    print('User was successfully registered')
    exit()


def login():
    username = input('Enter username: ')
    password = input('Enter password: ')
    get_data = open('register.txt', 'r').readlines()
    users_data = []
    for user in get_data:
        users_data.append(user.split())

    total_user = len(users_data)
    increment = 0
    login_success = 0
    while increment < total_user:
        usernames = users_data[increment][0]
        passwords = users_data[increment][1]
        if username == usernames and password == passwords:
            login_success = 1

        increment += 1

    if login_success == 1:
        print('Welcome ' + username)
    else:
        print('invalid username & password')


question = input('Do you have an account?/yes/no')

if question == 'yes':
    login()
else:
    register()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM