简体   繁体   中英

How do I read a certain variable inside a file.txt

I'm trying to make a fairly simple create account/login system, my question is how do I compare a string that's written inside a file.txt that contains all account data and compare it to what's being inserted while logging in?

def account_create():
    dataFile = open("credentials.txt", "w")
    name = input("Enter your name: ")
    user = input("Choose your username: ")
    pw = input("Choose your password: ")
    dataFile.write(name + " -\n")
    dataFile.write("Username: " + user + "\n")
    dataFile.write("Password: " + pw + "\n")
    dataFile.close()


def account_login():
    dataFile = open("credentials.txt", "r")
    userCheck = input("Enter your username: ")
    if userCheck == user:
        print("TEST")
    dataFile.close()

name = ""
user = ""
pw = ""

print("\nWelcome! Enter your option: ")

while True:
    try:
        option = int(input("1. Register an account || 2. Login to an existing account \n"))
        if (option < 0 or option > 2):
            raise ValueError
        break
    except ValueError:
        print("Invalid value, choose between 1 and 2")

if (option == 1):
    account_create()

else:
    account_login()

The easiest way to compare username and password to all accounts in the text file is to write a function that reads the complete text file and translates it to python objects. The problem is that the format you have chosen to store the data is easy to read by humans, but is not that easy to parse by a computer. In particular what do you do with a file that contains

someone -
Username: someone
Password: 1234
Password: 5566
Username: other person
Password: 0000

It is obviously not well defined but should a person be able to login with "someone" and "1234"? I mean the first three lines are okay? This is why I would recommend a new format: JSON can be easily read by humans and machines and python has a parser library built in. Here is some code to give you an example of how to work with data in this format:

import json

# The format for an account is {'name': ..., 'username': ..., 'password': ...}
# and accounts is a list of these dictionaries

def read_accounts(filename):
    with open(filename) as file:
        accounts = json.load(file)
    return accounts

def save_accounts(filename, accounts):
    with open(filename, 'w') as file:
        json.dump(accounts, file)

def add_account(accounts):
    name = input('Enter your name: ')
    username = input('Choose your username: ')
    password = input('Choose your password: ')
    accounts.append({'name': name, 'username': username, 'password': password})

def login_account(accounts):
    username = input('Choose your username: ')
    password = input('Choose your password: ')
    for account in accounts:
        if account['username'] == username:
            if account['password'] == password:
                print('You successfully logged in as', account['name'])
            else:
                print('Your password was incorrect')

Addendum

This way of storing the information still has a problem of ambiguity and the login function is unnecessarily complex. Imagine someone taking the same username that is already given to someone else. Currently it would only add a new user with the same username and (potentially) a different password. If a user then logs in two messages appear. One says that the login was successful and the other one that the password was wrong. This is not how it is supposed to work. We first change the data structure to a dictionary like this one

{'john': {'name': 'John Doe', 'password': 1234},
 'alex': {'name': 'Just Alex', 'password': 'alex'}}

The keys are the username and so no key can occur twice. In a second step there needs to be a check when adding a new user that he or she can not simply overwrite the previous account with that username:

# The read_accounts and save_accounts functions stay the same

def add_account(accounts):
    name = input('Enter your name: ')
    username = input('Choose your username: ')
    password = input('Choose your password: ')
    if username in accounts:
        raise RuntimeError('This username is already in use.')
    else:
        accounts['username']= {'name': name, 'password': password})

def login_account(accounts):
    username = input('Choose your username: ')
    password = input('Choose your password: ')
    if account[username]['password'] == password:
        print('You successfully logged in as', account[username]['name'])
    else:
        print('Your password was incorrect')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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