I am currently learning python and I started to write my first personal project. I created a very simple phone book which can get name and phone number and store it in a dict. But after I close the program the data is wiped out and it's not stored in some kind of DB or text file. I would like to add an additional feature where all the contacts are saved in text file (I assume a database will be quite hard for me at this point) and every time I open the program I access this text file with the previously saved contacts and I can apply some of the options like search, delete or show all contacts.
I am attaching my code, any additional comments would be appreciated.
contact_book = {}
while True:
user_choice = input("Select one of the following operations: \n [C] - Create a new contact \n [A] - Show all contacts"
"\n [S] - Search for a contact \n [D] - Delete contact \n [X] - Exit \n").upper()
if user_choice == "C":
contact_name = input()
contact_number = input()
contact_book[contact_name] = contact_number
if user_choice == "A":
for name, number in contact_book.items():
print(f'Contact name -> {name}. Phone number -> {number}')
if user_choice == "S":
search_name = input("Enter a contact name: ")
if search_name in contact_book:
print(f'{search_name} has been found in contact list. {search_name} phone number is {contact_book.get(contact_name)}')
else:
print(search_name, "is not found in the contact list.")
if user_choice == "D":
contact_to_delete = input("Enter the contact name you would like to delete: ")
if contact_to_delete in contact_book:
contact_book.pop(contact_to_delete)
print(f"{contact_to_delete} was removed from the contact list.")
else:
print(f"{contact_to_delete} has not been found.")
if user_choice == "X":
break
picklemodule, I'd also suggest e.g. Python as metaformat. As a new user here, please also take the tour and read How to Ask.