Phonebook with File I/O Modification

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# Title: Phonebook with File I/O Modification
# Author: Jack Rosenthal

# Kind programs always welcome their guests!
print("Welcome to the phone book!")

# Let's create an empty dictionary to store our entries in
book = {}

# Repeat this loop until they exit
while True:
    # Print the menu options
    print("What would you like to do?")
    print("    1 - Add an entry")
    print("    2 - Lookup an entry")
    print("    3 - Delete an entry")
    print("    4 - Load entries from file")
    print("    5 - Save entries to file")
    print("    6 - Exit")
    choice = input("Enter an option: ")

    # Add entry -- unchanged
    if choice == '1':
        name = input('Name: ')
        phone = input('Telephone Number: ')
        book[name] = phone

    # Lookup -- unchanged
    elif choice == '2':
        name = input('Name: ')
        print("Their number is:", book[name])

    # Delete -- unchanged
    elif choice == '3':
        name = input('Name: ')
        del book[name]

    # Load from file -- new
    elif choice == '4':
        # prompt user for filename
        fn = input("Filename: ")

        # open the file for reading
        f = open(fn, "r")

        # for each line in the file
        for line in f:
            # read the line as a colon separated list
            line = line.split(':')

            # the name is the first list item
            name = line[0]

            # the phone number is the second list item
            phone = line[1]

            # put the entry into the phonebook
            book[name] = phone

        # close the file when finished
        f.close()

    # Save to file -- new
    elif choice == '5':
        # prompt user for filename
        fn = input("Filename: ")

        # open the file for writing
        f = open(fn, "w")

        # for each entry in the phonebook
        for name in book.keys():
            # write the name, then a colon, then the number to a line
            f.write(name + ":" + book[name] + "\n")

        # close the file when finished
        f.close()

    # Quit -- unchanged
    elif choice == '6':
        # exit the loop
        break

    else:
        print('Invalid option.')