Trying to add user inputted variable into already existing list in a different file?

3407 views python
-3

I'm trying to make a permanent account creation for my game that i'm making which requires you to create an account before being able to play the game. I was trying to figure out how to add it and this is the closest I managed to get to adding it to the file. What happens is that it asks for the user to input their name and then it is meant to save it to the list in the first row of my variables.py, This is what I attempted to do

elif menu == '3':
        enterUsername = input('Please Enter A New Username')
        with open('variables.py', 'a') as text_file:
            print ("{}".format(enterUsername)[0], file=text_file)
        continue

Unfortunately this doesn't seem to work and it adds the name to the bottom of the file. There is existing names already in the list so I want to add it for example

main.py

User inputs = "TestUserName"

variables.py

authUsers = ['David', 'John', 'Ali','TestUserName']

I also attempted to change the [0] on line 4 to [authUsers] but it returned with an error saying that it can only be integers. As well as this I read the documents here https://developers.google.com/edu/python/lists . Thanks if anyone can help!

answered question

1 Answer

9

Create some functions to access your user file:

def makeSureFileExists(fn):
    """Create empty file if not exists."""
    def fileExists(fn):
        """Check if file exists."""
        import os.path
        return os.path.isfile(fn) 

    if not fileExists(fn):
        with open(fn, "w") as f:
            f.write("")

def addUser(fn, user):
    """Append user to file fn."""
    makeSureFileExists(fn)
    with open(fn,"a") as f:
        f.write(user+"\n")

def getAllUsers(fn):
    """Read file fn, return all users."""
    makeSureFileExists(fn)
    with open(fn,"r") as f:
        users=[x.strip() for x in f.readlines() if x.strip()]
    return users

filename  = "user.txt"

u = getAllUsers(filename);
print(u)                      # []

# add some users
addUser(filename,"John")
addUser(filename,"Mike")
addUser(filename,"Melitta")

u = getAllUsers(filename)     
print(u)                      # ['John', 'Mike', 'Melitta']

Essentially you do not modify your python-sourcecode but you create a config-file with users that you can read into a python list and process/check against.

The config file simply contains each user in one line, and can be read into your program again.

posted this

Have an answer?

JD

Please login first before posting an answer.