0
import ast


def register():
    cred_dict = {input("Username: "): input("Password: ")}

Collect known credentials - The error occurs at "cred_data = ast.literal_eval(file.read())" "unexpected EOF while parsing (, line 0)"

    with open("database.txt") as file:
        cred_data = ast.literal_eval(file.read())

Add new credentials

    cred_data.update(cred_dict)

Save credentials

    with open("database.txt", "a") as file:
        file.write(cred_data)


def login():

Load credentials

   print("--------LOGIN--------")
   with open("database.txt") as file:
        cred_pairs = ast.literal_eval(file.read())

Do the actual login

   return check_login(cred_pairs)


def check_login(credential_pairs):

Collect details

    try:
        username = input("Username: ")
        password = input("Password: ")
    except KeyboardInterrupt:


User cancelled

        print("Cancelled login")
        return False  # tell the program we haven't logged in

Does the user exist?

    if username in credential_pairs:

If true

        try:

Does their password match?

            if credential_pairs[username] == password:

If true

                print(f"Welcome, {username}.")
                return True  # tell the program we've logged in
            else:

If false

                print("Your password is incorrect")
                return False  # tell the program we haven't logged in

        except KeyError:

Something has gone horribly wrong!

            print("Something went wrong. Is your RAM broken?")
            return  

Tell the program something went wrong

        except KeyboardInterrupt:

User cancelled

            print("Cancelled login")
            return False  # tell the program we haven't logged in

    else:


        print("That user does not exist.")
        return False  # tell the program we haven't logged in

If execution ever reaches here you've been hacked

    return  # tell the program something went wrong


command = input("Would you like to [login] or [register]?\n>>> ")
if command == "register":
    register()

elif command == "login":
    login()
Tore
  • 1
  • 2

1 Answers1

0

ast is using compile to try and compile the string. This means the string must be able to be converted to an expression that can be evaluated. This looks like you are calling ast.literal_eval() on a blank file. Make sure there is a string in the file that is a valid expression. Just having a quoted string in the file should work e.g. 'test'

See the docs and also the answer to this question

Mikey Lockwood
  • 1,258
  • 1
  • 9
  • 22