0

I am using python pickle to maintain a contact list. I have 2 questions:

  1. After a new person is added, I don't see the whole list with all the persons is printed. only the new person is printed. what is wrong with the code?
  2. If I am going to delete one contact, how can I make the change to local file?

The code:

import pickle

class contact:
    person= {};    
    def add(self, name,contact):
        self.person[name] = contact;
        store2file(self.person);
        #print(self.contactlist);        
    def delete(self,name):
        del self.person[name];
        #print(self.person);  
    def modify(self,name,contact):
        self.person[name] = contact;
        store2file(self.person);  

def store2file(person):
    mycontactfile = 'contactlist.data';
    f = open(mycontactfile,'wb');
    pickle.dump(person,f);
    f.close();

    f = open(mycontactfile,'rb');
    storedcontact = pickle.load(f);
    print (storedcontact);

def main():
    mycontact = contact();
    option = input('Pls select option: 1 Add; 2 delete; 3 update: ');
    if option == '1':
        name = input('Enter the name: ');
        contactNo = input('Enter the contact number: ');
        mycontact.add(name,contactNo);
        store2file(mycontact);

    elif option =='2':
        name = input('Enter the name: ');
        mycontact.delete(name);
    elif option =='3':
        name = input('Enter the name: ');
        contactNo = input('Enter the contact number: ');
        mycontact.modify(name,contactNo);
    else:
        print('Pls select proper option');

main()
Hooked
  • 84,485
  • 43
  • 192
  • 261

2 Answers2

1

You are writing only the new person to the file overwriting existing data. You could write a list to the file (always reading the list and appending the new value before writing) to get the behavior you seem to want.

The workflow should be like this:

  • read current list from file
  • change stuff (add contact, remove contact)
  • maybe change more stuff ...
  • write list back to file

It is also possible (but more complex) to do it without a list:

  • append to the file as proposed by 'Guy' using 'a' instead of 'w' and/or pickle.dump() multiple times using the same file handler
  • pickle.load() multiple times on such a file until an EOFError occurs

To delete an entry from such a file you have to load every entry and save all the entries you still want back to the file (like filter()).

thammi
  • 444
  • 1
  • 4
  • 17
0

from python documentation http://docs.python.org/2/tutorial/inputoutput.html:

'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending;

to remove a contact, fine its line and delete it from the file, see Deleting a specific line in a file (python)

Community
  • 1
  • 1
Guy Gavriely
  • 11,228
  • 6
  • 27
  • 42