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

2024-04-26 02:19:47 发布

您现在位置:Python中文网/ 问答频道 /正文

在一个小项目中,我只是在乱翻字典来做一个密码系统。我是新手,所以请忍受我:

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

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

我怎样才能用最简单的方法把人们的帐户添加到字典中并保存下来呢?在

谢谢, 一个新程序员。在


Tags: newinputyourifaccessusernameaccountpassword
3条回答

您有几个选项,因此只需使用标准模块即可轻松保存dictionary。在注释中,您指向了JSON和{a2}。两者的基本用法都有非常相似的接口。在

在您学习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)

这将生成一个二进制文件:

^{pr2}$

现在使用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

当你的程序开始时

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 = {}

最后呢

^{pr2}$

您可以使用pickle模块来实现这一点。 这个模块有两种方法

  1. Pickling(dump):将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]

对于字典:

^{pr2}$

与您的代码相关:

  1. 通过pickle load()方法从userdetails文件获取值。在
  2. 使用raw_input从用户获取值。(使用input()表示Python 3.x
  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)
... 
>>> 

或者在文件不存在时处理异常 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:-

相关问题 更多 >