#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    1
    Rep Power
    0

    Need help writing to an external dictionary


    def register(users):
    unr = raw_input('Desired Username: ')
    if users.has_key(unr):
    print 'Sorry, username is already taken'
    else:
    pr = raw_input('Enter Password: ')
    users[unr] = pr

    from usernames import users

    register(users)

    I want to write the new username and password to the dictionary permanently, not just in the memory. So that the file will contain that information the next time the user tries to log in.

    I know that its insecure, but it is just for practice, how to write to the dictionary and external files. any help would be awesome!
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,900
    Rep Power
    481
    You could probably use memory mapped files but the usual answer would be "investigate pickle and shelve modules."

    http://docs.python.org/3/library
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    2
    Rep Power
    0
    This probably isn't what you wanted but you could write to a file.

    import ast

    users = {} # initialise users dict which initialise will update

    def writeToFile(): #call this whenever you change the dictionary
    userFile = open('users.txt', 'w')
    userFile.write(str(users))

    def initialise(): #initialise dictionary from last time
    usersFile = open('users.txt', 'r')
    userDict = ast.literal_eval(usersFile.read())
    for user in userDict: #you can edit globals within functions
    users[user] = userDict[user]
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    2
    Rep Power
    0
    probably also want to file.close() after each of those methods, and could put a try except around if you want too..

IMN logo majestic logo threadwatch logo seochat tools logo