如何打开一个Python pickle文件,追加到它,保存它,然后关闭它?

时间:2020-02-16 12:57:09

标签: 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 __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:未定义名称“用户”

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

我认为逻辑应该是:

1)文件存在吗?
如果是-不执行任何操作
如果为N-使用示例数据创建

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

2 个答案:

答案 0 :(得分:1)

我发现的问题是您实际上没有在以下行中使用已加载的泡菜数据:

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

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

答案 1 :(得分:0)

尝试此代码:

try:
    users = pickle.load(open("users.pickle", "rb"))
except (OSError, IOError) as f:
    foo = 3
    print("except")
    pickle.dump(users, open("users.pickle", "wb"))

quit()之外还有:

with open('users.pickle', 'wb') as f:
    pickle.dump(users, f)
quit()