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

3407 views python

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, This is what I attempted to do

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

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

User inputs = "TestUserName"

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 . Thanks if anyone can help!

answered question

1 Answer


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:

def addUser(fn, user):
    """Append user to file fn."""
    with open(fn,"a") as f:

def getAllUsers(fn):
    """Read file fn, return all users."""
    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

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?


Please login first before posting an answer.