如何打开Python pickle文件、追加、保存和关闭它?
这是我的密码:如何打开Python pickle文件、追加、保存和关闭它?,python,pickle,Python,Pickle,这是我的密码: import pickle class User: def __init__(self, username, password): self.username = username self.password = password def set_password(self): self.password = input("Enter NEW password > ") def
import pickle
class User:
def __init__(self, username, password):
self.username = username
self.password = password
def set_password(self):
self.password = input("Enter NEW password > ")
def __get_password(self):
return self.password
def __get_username(self):
return self.username
def change_password(self):
my_password = input("Enter your CURRENT password > ")
if my_password == User.__get_password(self):
self.set_password()
else:
print("Please try again")
def display_details(self):
print()
print("Username and password")
print("---------------------")
print("username is: ", User.__get_username(self))
print("password is: ", User.__get_password(self))
print()
def __repr__(self):
return f'username: {self.username}'
users = [User("MichaelPalin", "P4rr0t"), User("EricIdle", "M0nty"), User("TerryJones", "Pyth0n")]
try:
foo = pickle.load(open("users.pickle", "rb"))
except (OSError, IOError) as f:
foo = 3
pickle.dump(foo, open("users.pickle", "wb"))
# with open('users.pickle', 'wb') as f:
# pickle.dump(users, f)
def find_user(name):
for user in users:
if user.username == name:
return user
def add_user():
user = input("Enter NEW user > ")
password = input(f"Enter password for {user} > ")
users.append(User(user, password))
def delete_user():
delete_user = input("Enter the user you wish to remove > ")
user = find_user(delete_user)
if user:
users.remove(user)
print('done')
else:
print(f'user {delete_user} not found')
def change_password():
my_password = input("Enter your CURRENT password > ")
change_password()
def display_users():
for user in users:
print(user)
def invalid_entry(): # Response for invalid entries to menu.
print("Invalid entry, please try again")
print()
def menu(): # Display menu, prompt for and accept keyboard choice
print("Please select one of the following:")
print()
print("Enter a if you want to add a new user")
print("Enter d if you want to delete a user")
print("Enter f if you want to find a user")
print("Enter c if you want to change your password")
print("Enter u if you want to display a list of users")
print("Enter q if you want to Quit")
choice = input("")
return choice
while True:
menu_choice = menu()
if menu_choice.lower() == "a":
add_user()
elif menu_choice.lower() == "d":
delete_user()
elif menu_choice.lower() == "f":
find_user()
elif menu_choice.lower() == "c":
change_password()
elif menu_choice.lower() == 'u':
display_users()
elif menu_choice.lower() == "q":
print("Goodbye")
with open('users.pickle', 'wb') as f:
pickle.dump(users, f)
quit()
else:
invalid_entry()
但它不能正常工作,因为每次程序运行时都会覆盖pickle文件。我猜罪魁祸首是用户
行,但如果是这样的话,我不知道如何解决问题。我尝试将整行移动到try
部分的底部,与pickle.dump
行对齐,但这只是抛出了一个错误:
NameError:未定义名称“用户”
有人能帮我吗?我已经试着这样做了大约两周了,现在我越来越沮丧了。我在网上看过很多相关的教程,现在看到的很多链接都是紫色的,但我似乎不知道如何编写代码来创建正确的逻辑流
我认为逻辑应该是:
1) 文件是否存在?如果Y-什么也不做
如果N-使用示例数据创建它 2) 用户是否要创建新登录?
如果是Y-将登录名附加到文件
如果N-do nothing我发现的问题是,您实际上没有在这些行中使用加载的pickle数据:
users = [User("MichaelPalin", "P4rr0t"), User("EricIdle", "M0nty"), User("TerryJones", "Pyth0n")]
try:
foo = pickle.load(open("users.pickle", "rb"))
except (OSError, IOError) as f:
foo = 3
pickle.dump(foo, open("users.pickle", "wb"))
您将文件加载到foo
中,但从不使用它,而且您的异常也没有多大意义,请尝试将该块更改为以下内容:
try:
users = pickle.load(open("users.pickle", "rb"))
except (OSError, IOError) as f:
users = [User("MichaelPalin", "P4rr0t"), User("EricIdle", "M0nty"), User("TerryJones", "Pyth0n")]
pickle.dump(foo, open("users.pickle", "wb"))
现在,您将尝试加载预先制作的文件,如果失败,请生成默认文件,然后尝试以下代码:
try:
users = pickle.load(open("users.pickle", "rb"))
except (OSError, IOError) as f:
foo = 3
print("except")
pickle.dump(users, open("users.pickle", "wb"))
另外,退出()outside with:
with open('users.pickle', 'wb') as f:
pickle.dump(users, f)
quit()
pickle是一个倾斜的结构,你可以在不修改头部的情况下附加一些东西的想法是不正确的。@tripleee-恐怕我不知道你的意思。我试着在谷歌上搜索“pickle是一个斜结构”,但我还是不知道。他的意思是pickle不是一个你可以附加的文本文件,它是一个你必须重写的二进制对象,这就是你想要的do@Nullman-我明白了,谢谢。谢谢!!!终于破解了!哈利路亚!!事实上,我在尝试将
用户
行放入该块时已经走得不远了,但我做得不对。再次感谢。在回答问题时,试着解释一下为什么你的解决方案回答了原始海报的问题。这将帮助其他用户快速确定您的答案是否也适用于他们的问题。