Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- from pathlib import Path
- # Potential extension: make contacts an object
- def get_filename():
- filename = input("\nFilename: ")
- if filename[-4:] != ".txt":
- filename += ".txt"
- return filename
- def get_existing_filename():
- while True:
- filename = get_filename()
- file = Path(filename)
- if file.is_file():
- return filename
- else:
- print(f"'{filename}' does not exist in this directory.")
- def find_contact():
- filename = get_existing_filename()
- file = open(filename, "r")
- contact_name = input("\nContact name: ").lower()
- lines = file.read().splitlines()
- found = False
- for line in lines:
- if contact_name in line:
- print(f"{contact_name.title()}: {line[line.index(':') + 1:]}")
- found = True
- break
- if not found:
- print(f"'{contact_name.title()}' was not found in the contact book.")
- file.close()
- menu()
- def create_contact():
- while True:
- print("\nCreate contact\n1) Add to existing contact book\n2) Create new contact book\n")
- try:
- option = int(input("Option: "))
- if option == 1:
- filename = get_existing_filename()
- file = open(filename, "a")
- contact_name = input("\nContact name: ").lower()
- while True:
- try:
- phone_number = input("\nPhone number: ")
- int(phone_number)
- break
- except ValueError:
- print("Please enter a valid phone number.")
- file.write(f"{contact_name}:{phone_number}\n")
- file.close()
- print(f"Added {contact_name.title()} to the contact book.")
- break
- elif option == 2:
- while True:
- filename = get_filename()
- file = Path(filename)
- if file.is_file():
- print("Please enter a filename that does not exist.")
- else:
- break
- file = open(filename, "w+")
- file.close()
- print(f"Created a new contact book called '{filename}'.")
- break
- else:
- print("Please choose an option between 1 and 2.")
- except ValueError:
- print("Please choose an option between 1 and 2.")
- menu()
- def menu():
- while True:
- print("\nMenu\n1) Find contact\n2) Create contact\n3) Quit\n")
- try:
- option = int(input("Option: "))
- if option == 1:
- find_contact()
- elif option == 2:
- create_contact()
- elif option == 3:
- sys.exit()
- else:
- print("Please choose an option between 1 and 3.")
- except ValueError:
- print("Please choose an option between 1 and 3.")
- print("Contact Book")
- menu()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement