Bob
Bob

Reputation: 21

How to save the data gathered in the address book?

I am using a file in text edit ubuntu. I am trying to figure out a way to save it. When I close the python shell and rerun it, it deletes all past info. Would I have to make a new function?

AdressBook  = '/home/bookworm/AdressBook.txt'
contacts = {}

def write():
    Data = open(AdressBook,'w')
    for name, many in contacts.items():
        Data.write(name + ',' + many)
    Data.close()

def read():
    Data = open(AdressBook, 'r')
    stuff = Data.read()
    print(stuff)
    Data.close()


user = input('Would you like to acess your adress book?')
if user == 'yes' or 'yep' or 'y' or 'Yes' or 'YES!' or 'YES' or 'Yurp' or 'Yeppers' or 
'si'or'1':

It is only the deleted and added contacts to be saved

    while user != 5:
        user = input('''Select One:
Press 1 to update
Press 2 to display all contacts
Press 3 to search adress book
Press 4 to delete contacts
Press 5 to quit your adress book.''')

        if user == '1':
            name = input('Please enter the name of the contact that you would like to add.')
            contact = input('Please enter the contact information of %s.'%name)
            Name = '\n' + name
            contacts.update( {Name : contact} )
            print('')
            print('%s was added to your adress book!' %name)
            print('')
            write()

        elif user == '2':
            read()

To call read function

        elif user == '3': 
            name = input('What is the name of the person whose contacts you need?')
            print(contacts[name])

To delete a contact

        elif user == '4':
            name = input('Type in the name of the contact that you would like to delete.')
            del contacts[name]
            print('Your contact List has sucessfully deleted %s' %name)
            write()

        elif user == '5':
            print('Thank you for acessing your adress book!')
            exit()

else:
    exit()

Upvotes: 2

Views: 103

Answers (1)

Aviral Verma
Aviral Verma

Reputation: 548

Your file becomes empty everytime because you are taking contacts = {} in the start of the program. So instead of creating an empty dictionary, you need to initialize the dictionary with the file contents in the starting.


AdressBook  = '/home/bookworm/AdressBook.txt'
contacts = initialize_contacts()

def write():
    Data = open(AdressBook,'w')
    for name, many in contacts.items():
        Data.write(name + ',' + many + '\n')
    Data.close()

def read():
    Data = open(AdressBook, 'r')
    stuff = Data.read()
    print(stuff)
    Data.close()
    return stuff

def initialize_contacts():
    data = read()
    contact_list = data.split('\n')
    for contact in contact_list[:-1]:
        name,cont = contact.split(',')
        contacts[name] = cont

Upvotes: 1

Related Questions