Я не уверен, что получил ответ, но возникла небольшая проблема с отступом (по моему мнению) ... отформатированный код такой, как показано ниже.
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")]
with open('mypickle.pickle', 'wb') as f:
pickle.dump(users, f)
def find_user(name):
for user in users:
if user.username == name:
return user
def display_users():
for user in users:
print(user)
def add_user():
user = input("Enter NEW user > ")
password = input(f"Enter password for {user} > ")
users.append(User(user, password))
with open('users.pickle', 'wb') as f:
pickle.dump(users, f)
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 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 1 if you want to add a new user")
print("Enter 2 if you want to delete a user")
print("Enter 3 if you want to change your password")
print("Enter u if you want to display a list of users")
print("Enter 4 if you want to Quit")
choice = input("")
return choice
while True:
menu_choice = menu()
if menu_choice == "1":
add_user()
elif menu_choice == "2":
delete_user()
elif menu_choice == "3":
change_password()
elif menu_choice.lower() == 'u':
display_users()
elif menu_choice == "4":
print("Goodbye")
quit()
else:
invalid_entry()
Это дает мне ожидаемый результат, как показано ниже .
Please select one of the following:
Enter 1 if you want to add a new user
Enter 2 if you want to delete a user
Enter 3 if you want to change your password
Enter u if you want to display a list of users
Enter 4 if you want to Quit
1
Enter NEW user > TestUser
Enter password for TestUser > TestPassword
Please select one of the following:
Enter 1 if you want to add a new user
Enter 2 if you want to delete a user
Enter 3 if you want to change your password
Enter u if you want to display a list of users
Enter 4 if you want to Quit
u
username: MichaelPalin
username: EricIdle
username: TerryJones
username: TestUser
Please select one of the following:
Enter 1 if you want to add a new user
Enter 2 if you want to delete a user
Enter 3 if you want to change your password
Enter u if you want to display a list of users
Enter 4 if you want to Quit
4
Goodbye
Чтобы загрузить обновленный файл "users.pickle", я набрал следующее.
with open("/FullPathToPickleFile/users.pickle","rb") as Handle:
pickle.load(Handle)
, и это дало мне следующий вывод.
[username: MichaelPalin, username: EricIdle, username: TerryJones, username: TestUser]
Как видите, TestUser был добавлен. если бы вы хотели видеть обновленных пользователей, как в заархивированном файле, я бы поместил вышеупомянутые две строки кода в display_users (), как показано ниже.
def display_users():
with open("/FullPathToPickleFile/users.pickle","rb") as Handle:
print(pickle.load(Handle))
С этими изменениями вы сможете обновить пользователей и увидеть обновленный список.
Это то, что вы хотели?