回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我正在尝试用Python编写一个简单的密码存储程序,它看起来非常简单,所以我想知道我是不是用错了shelve。</p>
<p>我有主.py文件:</p>
<pre><code>import shelve
passwords = shelve.open('./passwords_dict.py')
choice = raw_input("Add password (a) or choose site (c)?")
if choice[0] == 'a':
site_key = raw_input("Add for which site? ").lower()
userpass = raw_input("Add any info such as username, email, or passwords: ")
passwords[site_key] = userpass
else:
site = raw_input("Which site? ").lower()
if site in passwords:
print "Info for " + site + ": " + passwords[site]
else:
print site, "doesn't seem to exist!"
print "Done!"
passwords.close()
</code></pre>
<p>另一个文件passwords_dict.py只是一个空字典。</p>
<p>但是当我试图运行程序时,我得到了一个错误:</p>
<pre><code>Traceback (most recent call last):
File "passwords.py", line 3, in <module>
passwords = shelve.open('passwords_dict.py')
File "/usr/lib/python2.7/shelve.py", line 239, in open
return DbfilenameShelf(filename, flag, protocol, writeback)
File "/usr/lib/python2.7/shelve.py", line 223, in __init__
Shelf.__init__(self, anydbm.open(filename, flag), protocol, writeback)
File "/usr/lib/python2.7/anydbm.py", line 82, in open
raise error, "db type could not be determined"
anydbm.error: db type could not be determined
</code></pre>
<p>当我尝试改用anydbm时,会出现以下错误:</p>
<pre><code>Traceback (most recent call last):
File "passwords.py", line 3, in <module>
passwords = anydbm.open('passwords_dict.py')
File "/usr/lib/python2.7/anydbm.py", line 82, in open
raise error, "db type could not be determined"
anydbm.error: db type could not be determined
</code></pre>
<p>当我尝试使用dbm时,会出现以下错误:</p>
<pre><code>Traceback (most recent call last):
File "passwords.py", line 3, in <module>
passwords = dbm.open('./passwords_dict.py')
dbm.error: (2, 'No such file or directory')
</code></pre>
<p>我做错什么了?有没有另一种方法来存储字典,并且仍然能够使用用户输入来提取密钥(而不是整个字典,我想pickle就是这样做的)?</p>