如何获取字典以保存下次运行的新添加项目?

时间:2015-06-04 15:29:17

标签: python python-2.7 dictionary

我正在学习Python,而且我已经制作了一个密码储物柜,可以将密码复制到剪贴板中。如果它找不到您要查找的帐户,则会询问您是否要为该帐户添加密码,并使用新项目更新字典。

我的问题是每次运行时字典都会更新,但是当我再次运行它时会丢失新项目。因此,每次运行都不会继续下一次。

以下是代码:

#! python2
# a password locker program in Python

# Dict to store the account: password
PASSWORDS = {"email": "password",
             "blog": "password",
             "luggage": "password",
             "house": "password"}

import sys, pyperclip # Handles command line arguments
if len(sys.argv) < 2: # sys.argv takes 2 arguments, the first is the filename, the second is the first command line arg.
    # if the argument entered is less than 2, print the below
    print "Usage: Python pw.py [acount] - copy account password"
    sys.exit() # done with sys.argv

account = sys.argv[1] # first command line argv is the account name. We can just use sys.argv[1], but that would be cryptic and confusing.

if account in PASSWORDS: # if the account name (the key) is in PASSWORDS
    pyperclip.copy(PASSWORDS[account]) # pyperclip.copy() just copies things. PASSWORDS[account] will call the value to be copied
    print "Password for", account, "has been copied."
else:
    print "Would you like to add a password for this account?"
    answer = raw_input("Enter YES or NO: ")
    if answer.lower() == "yes":
        print "Enter your password for", account, ". Make it hard!"
        password = raw_input("Password: ")
        PASSWORDS[account] = password # another way to put it is: PASSWORD.update({account: password})
        print "Account and password added to database!"
    else:
        print "DONE"

print PASSWORDS

这就是我想要它做的事情:如果我搜索一个不存在的帐户,请向我询问密码,然后保存。当我在新的运行中再次运行程序时,该键和值就在那里,并将被复制到我的剪贴板。

我希望将新项目添加到程序本身的PASSWORDS dict中,并在下次使用它作为参考。

使用Pycharm运行Mac OS。使用Python 2.7

由于

(当然,计划的密码以及我真正的密码。杜)

1 个答案:

答案 0 :(得分:4)

Python字典不会比脚本的执行持续更长时间。查看python pickle模块,用于序列化字典并在程序完成时将其写入文件,然后在完成时将字典反序列化并将字典加载到内存中。

我注意到有几种不同的学习和操作的方法,但是pickle包含在标准的python 2.7中,在我看来,这是最容易学习的。 Here是一个简单的教程。

相关问题