我是Python的新手,我正在编写一个Python 2.7代码来存储帐户信息(用户名和密码)以练习使用类和编码。我们的想法是创建一个帐户,创建用户名和密码,并将用户名和密码存储在以字典为密钥的字典中,然后使用Pickle模块将对象存储在文本文件中。还存在用于显示存储帐户的命令,当然还可以根据帐户密钥检索用户名和密码。
现在它的编写方式我必须为每个附加的字典键和项目添加整个文件,然后截断原始文件并重新选择整个字典。这是最好的方法吗?我试图通过我的代码提高效率,看起来我写的方式并不像我想的那样顺利,虽然它似乎工作得相当好(很快就会增加错误处理) )。非常感谢我能否直接将pickle数据流附加到文本文件以及有关约定或代码效率的任何其他评论
import pickle
class Create(object):
def __init__(self, account, un_and_pass, pass_dump):
self.account = account
self.un_and_pass = un_and_pass
self.pass_dump = pass_dump
def write(self, account, un_and_pass, pass_dump):
storage_file = open("Storage.txt", "r")
pass_dump = pickle.load(storage_file)
storage_file.close()
pass_dump[account] = un_and_pass
storage_file = open("Storage.txt", "w+")
pickle.dump(pass_dump, storage_file)
storage_file.close()
class Retrieve(object):
def __init__(self, account):
self.account = account
def display(self, account):
storage_file = open("Storage.txt", "r")
pass_dump = pickle.load(storage_file)
un_and_pass = str(pass_dump[account])
un_and_pass = un_and_pass.replace('(',' ').replace(')',' ').replace('\'',' ')
username, password = un_and_pass.split(",")
print "Username for", account, "is",username, "\nPassword for", account, "is",password
storage_file.close()
on = True
while on == True:
action = raw_input("Please select an option (store, retrieve, display accounts, quit): ")
if "store" in action:
account = raw_input("what is this account for?: ")
un = raw_input("what is the username?: ")
password = raw_input("what is the password?: ")
un_and_pass = un, password
pass_dump = {}
c = Create(account, un_and_pass, pass_dump)
c.write(account, un_and_pass, pass_dump)
elif "retrieve" in action:
account = raw_input("Enter account: ")
d = Retrieve(account)
d.display(account)
elif "display" in action:
storage_file = open("Storage.txt", "r")
pass_dump = pickle.load(storage_file)
print "Stored accounts are:"
for item in pass_dump:
print item
elif "quit" in action:
print "Goodbye"
on = False
else:
print "Command not valid"