2

I'm trying to save a username register input into a list permanently (as in it will still be there even after I close the file) where I can then access it. I'm trying to create a login system. Sorry if this question sounds very idiotic because I'm an absolute newbie to coding.

Example:

list_of_users = ['Elias', 'James']
new_user = None
new_user = input('Create new user: ')
list_of_users.append(new_user)
martineau
  • 119,623
  • 25
  • 170
  • 301
palmolive
  • 21
  • 1
  • 1
    Is saving to a text file good enough? – Martheen May 01 '20 at 00:14
  • You can save and load the `list_of_users` variable using the `pickle` module — see [Saving an Object (Data persistence)](https://stackoverflow.com/questions/4529815/saving-an-object-data-persistence). – martineau May 01 '20 at 01:29

2 Answers2

1

You can use the builtin python module, shelve to give you dict like syntax for your mini-"database". This will let you save arbitrary python objects to it (at least pickleable ones).

import shelve 

db = shelve.open(".db")

users = db.get("users", [])
users.append(input("Create new user: "))
...
db["users"] = users

db.close()
modesitt
  • 7,052
  • 2
  • 34
  • 64
0

I'd suggest loading and saving your list to a local txt file:

if os.path.isfile("my_list.txt"):
    # Import your list
    list_of_users = open("my_list.txt","r").read().split("\n")
else:
    list_of_users = []

# Ask for new users
new_user = input('Create new user: ')

list_of_users.append(new_user)

# Save your list:
with open("my_list.txt","w") as f:
    f.write("\n".join(list_of_users))

Yaakov Bressler
  • 9,056
  • 2
  • 45
  • 69