如何保存字典Python编辑:可以使用pickle

时间:2015-02-13 12:08:48

标签: python dictionary passwords

对于一个小项目我只是乱搞字典来制作密码系统。我是新手,所以忍受我:

users = {"user1" : "1234", "user2" : "1456"}

print ("Welcome to this password system")
print ("Please input your username")

choice = input ("")

print ("Please enter your password")

choice2 = input ("")

if (choice in users) and (choice2 == users[choice]):
    print ("Access Granted")
else:
    print ("Access Denied. Should I create a new account now?")
    newaccount = input ("")
    if newaccount == "yes" or "Yes":
        print ("Creating new account...")
        print ("What should your username be?")
        newuser = input ("")
        print ("What should your password be?")
        newpass = input ("")
        users.update({newuser:newpass})

我正在使用更新将其添加到字典中,但是当我退出程序时,新的更新没有注册?

我怎样才能以最简单的方式将人们的帐户添加并保存到字典?

谢谢, 一个新的程序员。

3 个答案:

答案 0 :(得分:0)

程序启动时

import os
import json
FILEPATH="<path to your file>" 
try:
   with open(FILEPATH) as f: #open file for reading
       users = json.loads(f.read(-1)) #read everything from the file and decode it
except FileNotFoundError:  
   users = {}

最后

with open(FILEPATH, 'w') as f: #open file for writing
     f.write(json.dumps(users)) #dump the users dictionary into file

答案 1 :(得分:0)

您有多个选项,因此只使用标准模块轻松保存字典 。在评论中,您指向JSONPickle。两者都有非常相似的基本用法界面。

在学习Python的时候,我建议你看一下非常好的Dive Into Python 3 ‣ Ch 13: Serializing Python Objects。这将回答您关于使用其中一个模块或其他模块的大部分问题(您的老师的问题?)。


作为补充,这里有一个使用Pickle的非常简单的例子:

import pickle
FILEPATH="out.pickle"

# try to load
try:
    with open(FILEPATH,"rb") as f:
        users = pickle.load(f)
except FileNotFoundError:
   users = {}

# do whantever you want
users['sylvain'] = 123
users['sonia'] = 456

# write
with open(FILEPATH, 'wb') as f:
     pickle.dump(users, f)

这将生成二进制文件:

sh$ hexdump -C out.pickle
00000000  80 03 7d 71 00 28 58 07  00 00 00 73 79 6c 76 61  |..}q.(X....sylva|
00000010  69 6e 71 01 4b 7b 58 05  00 00 00 73 6f 6e 69 61  |inq.K{X....sonia|
00000020  71 02 4d c8 01 75 2e                              |q.M..u.|
00000027

现在使用JSON:

import json
FILEPATH="out.json"

try:
    with open(FILEPATH,"rt") as f:
        users = json.load(f) 
except FileNotFoundError:
   users = {}

users['sylvain'] = 123
users['sonia'] = 456

with open(FILEPATH, 'wt') as f:

基本上使用相同的代码,将pickle替换为json 将文件打开为 text 。制作文本文件:

sh$ $ cat out.json 
{"sylvain": 123, "sonia": 456}
#                             ^
#                         no end-of-line here

答案 2 :(得分:0)

您可以使用pickle模块。 该模块有两种方法,

  1. 腌制(转储):将Python对象转换为字符串表示形式。
  2. 取消(加载):从存储的字符串表示中检索原始对象。
  3. https://docs.python.org/3.3/library/pickle.html 代码:

    >>> import pickle
    >>> l = [1,2,3,4]
    >>> with open("test.txt", "wb") as fp:   #Pickling
    ...   pickle.dump(l, fp)
    ... 
    >>> with open("test.txt", "rb") as fp:   # Unpickling
    ...   b = pickle.load(fp)
    ... 
    >>> b
    [1, 2, 3, 4]
    

    字典:

    >>> import pickle
    >>> d = {"root_level1":1, "root_level2":{"sub_level21":21, "sub_level22":22 }}
    >>> with open("test.txt", "wb") as fp:
    ...     pickle.dump(d, fp)
    ... 
    >>> with open("test.txt", "rb") as fp:
    ...     b = pickle.load(fp)
    ... 
    >>> b
    {'root_level2': {'sub_level21': 21, 'sub_level22': 22}, 'root_level1': 1}
    

    与您的代码相关:

    1. 通过pickle load()方法从userdetails文件中获取值。
    2. 使用raw_input从用户获取值。 (使用input()进行Python 3.x
    3. 检查访问是否被授予。
    4. 创建新用户但检查用户名是否已存在于系统中。
    5. 在用户词典中添加新用户详细信息。
    6. pickle dump()方法将用户详细信息转储到文件中。
    7. 将默认值设置为file:

      >>> import pickle
      >>> file_path = "/home/vivek/workspace/vtestproject/study/userdetails.txt"
      >>> users = {"user1" : "1234", "user2" : "1456"}
      >>> with open(file_path, "wb") as fp:
      ...     pickle.dump(users, fp)
      ... 
      >>> 
      

      或者在文件不存在时处理异常 e.g。

      try:
          with open(file_path,"rb") as fp:
              users = pickle.load(fp)
      except FileNotFoundError:
          users = {}
      

      代码:

      import pickle
      import pprint
      
      #- Get User details
      file_path = "/home/vivek/workspace/vtestproject/study/userdetails.txt" 
      with open(file_path, "rb") as fp:   # Unpickling
        users = pickle.load(fp)
      
      print "Existing Users values:"
      pprint.pprint(users)
      
      
      print "Welcome to this password system"
      choice = raw_input ("Please input your username:-")
      choice2 = raw_input ("Please enter your password")
      
      if choice in users and choice2==users[choice]:
          print "Access Granted"
      else:
          newaccount = raw_input("Should I create a new account now?Yes/No:-")
          if newaccount.lower()== "yes":
              print "Creating new account..."
              while 1:
                  newuser = raw_input("What should your username be?:")
                  if newuser in users:
                      print "Username already present."
                      continue
                  break
      
              newpass = raw_input("What should your password be?:")
              users[newuser] = newpass
      
          # Save new user
          with open(file_path, "wb") as fp:   # pickling
              pickle.dump(users, fp)
      

      输出:

      $ python test1.py
      Existing Users values:
      {'user1': '1234', 'user2': '1456'}
      Welcome to this password system
      Please input your username:-user1
      Please enter your password1234
      Access Granted
      
      $ python test1.py
      Existing Users values:
      {'user1': '1234', 'user2': '1456'}
      Welcome to this password system
      Please input your username:-test
      Please enter your passwordtest
      Should I create a new account now?Yes/No:-yes
      Creating new account...
      What should your username be?:user1
      Username already present.
      What should your username be?:test
      What should your password be?:test
      
      $ python test1.py
      Existing Users values:
      {'test': 'test', 'user1': '1234', 'user2': '1456'}
      Welcome to this password system
      Please input your username:-