gpt4 book ai didi

python - 如何打开 Python pickle 文件、追加、保存和关闭它?

转载 作者:行者123 更新时间:2023-12-01 06:24:04 25 4
gpt4 key购买 nike

这是我的代码:

 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 文件都会被覆盖。我猜罪魁祸首是 users 行,但如果是这样的话,我不知道如何解决问题。我尝试将整行移动到 try 部分的底部,与 pickle.dump 行对齐,但这只是引发了一个错误:

NameError: name 'users' is not defined

有人可以帮我吗?我已经尝试这样做大约两周了,但我越来越沮丧。我在网上查看了很多相关教程,以至于我看到的许多链接现在都是紫色的,但我似乎无法弄清楚如何编写代码来创建正确的逻辑流程。

我认为逻辑可能应该是:

1) 文件是否存在?
如果是 - 什么都不做
如果 N - 使用示例数据创建它

2) 用户是否要创建新的登录名?
如果是 - 将登录名附加到文件
如果 N - 不执行任何操作

最佳答案

我发现的问题是,您实际上并没有在这些行中使用加载的 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 中,但从未使用它,并且您的异常没有多大意义,请尝试将该 block 更改为以下内容:

 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"))

现在您将尝试加载预制文件,并在失败时生成默认文件

关于python - 如何打开 Python pickle 文件、追加、保存和关闭它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60248665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com