繁体   English   中英

如何保存字典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

您有几种选择,因此仅使用标准模块即可轻松保存字典。 在注释中,您指向JSONPickle 两者都具有非常相似的基本用法界面。

在学习Python时,我建议您看一看非常好的Dive Into Python 3第13章:序列化Python对象 这将回答您关于使用其中一个模块或另一个模块的大部分问题( 以及您老师的问题?)。


作为补充,这里有一个使用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 打开该文件为文本 生成文本文件:

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

你可以使用pickle模块。 这个模块有两种方法,

  1. Pickling(转储) :将Python对象转换为字符串表示形式。
  2. 取消(加载) :从存储的字符串表示中检索原始对象。

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()方法pickle dump()用户详细信息转储到文件中。

将默认值设置为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)
... 
>>> 

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM