所以我对Python很陌生,几天前开始学习...我遇到了一个练习项目,我们将在其中创建一个密码储物柜来存储帐户及其各自的密码。
#! python3
# pw.py - An insecure password locker program.
PASSWORDS = {'email': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6',
'blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt',
'luggage': '12345'}
import sys
if len(sys.argv) < 2:
print('Usage: python pw.py [account] - copy account password')
sys.exit()
account = sys.argv[1] # first command line arg is the account name
if account in PASSWORDS:
pyperclip.copy(PASSWORDS[account])
print('Password for ' + account + ' copied to clipboard.')
else:
print('There is no account named ' + account)
这就是代码。因此,我想到了一种方法,如果该帐户之前不存在,则使用新信息更新 PASSWORDS 字典。所以我将这几行代码添加到else语句中
print('Input the password for the said account to update the info.')
PASSWORDS[account] = input()
print('Info updated!')
我现在面临的问题是,添加到字典中的值在程序完成后不会保留。
最佳答案
密码管理始终是一个非常微妙的话题,但由于您刚刚开始并且不会询问安全性,所以让我们看看如何以非常简单的方式加载和编写一个简单的 JSON 文件。
首先,让我们将实际数据移动到一个单独的文件中,我们可以将其命名为database.json
:
{"email": "F7minlBDDuvMJuxESSKHFhTxFtjVB6",
"blog": "VmALvQyKAxiVH5G8v01if1MLZF3sdt",
"luggage": "12345"}
然后我们像这样更改应用程序代码:
#!/usr/env python3
"""
pw.py - An insecure password locker program.
"""
import sys
import pyperclip
import json
import os
# The path to the database file
DB_FILE = "~/Desktop/database.json"
def main():
if len(sys.argv) < 2:
print('Usage: python pw.py [account] - copy account password')
sys.exit()
account = sys.argv[1] # first command line arg is the account name
db = os.path.expanduser(DB_FILE)
with open(db) as f:
data = json.load(f) # Load a dictionary for disk
if account in data:
pyperclip.copy(data[account])
print('Password for ' + account + ' copied to clipboard.')
else:
print('There is no account named ' + account)
print('Input the password for the said account to update the info.')
new_passwd = {account: input()} # create a dictionary with the new account data
data.update(new_passwd) # update the main dictionary with the new data
with open(db, 'w') as f:
json.dump(data, f) # convert to JSON and write to disk
print('Info updated!')
if __name__ == "__main__":
main()
对于这样一个简单的任务,您可以使用多种文件格式。 JSON 是一种以逻辑且易于理解的方式映射到 Python 字典的格式,但您也可以在 CSV 中实现它,而不会增加太多复杂性。但在这种应用程序中,您很快就会感到需要更实用和更强大的东西。例如,随着数据库的增长,将整个数据库加载到内存中可能开始变得不切实际。它可能会引发更多的安全问题。
花点时间学习这些基础知识,然后探索 module sqlite
。它允许在单文件关系数据库中使用 SQL,并将为您强大的应用程序和进一步学习铺平道路。
关于python - 更新字典的键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52735995/