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

How to save a dictionary Python Edit: Can use pickle

对于一个小项目,我只是在弄乱字典来制作密码系统。我是新手,所以请多多包涵:

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})

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

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

谢谢, 新程序员。

程序启动时

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

您有多种选择,因此仅使用 标准 模块轻松 保存字典。在评论中,你在哪里指向 JSON and Pickle。两者的基本用法界面非常相似。

在你学习的过程中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。生成 text 文件:

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

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

  1. Pickling(dump):将 Python 个对象转换为字符串表示形式。
  2. Unpickling(load):从存储的字符串表示中检索原始对象。

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 从用户那里获取值。 (对 Python 3.x 使用 input()
  3. 检查是否授予访问权限。
  4. 创建新用户但检查用户名是否已存在于系统中。
  5. 在用户字典中添加新用户详细信息。
  6. 通过 pickle dump() 方法将用户详细信息转储到文件中。

为文件设置默认值:

>>> 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)
... 
>>> 

或者当文件不存在时处理异常 例如

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:-