Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Program for storing contacts via command line
- Usage:
- Add: -a <first> <last> <number>
- Remove: -rm <first> <last> <number>
- List: -l
- """
- import argparse
- import pickle
- #Argument parser
- parser = argparse.ArgumentParser(description="Save contacts in this program")
- group = parser.add_mutually_exclusive_group()
- group.add_argument('-a', '--add', action='store_true', help='add a contacts: -a <first> <last> <number>')
- group.add_argument('-rm', '--remove', action='store_true', help='delete a contact: -rm <first> <last> <number>')
- parser.add_argument('-l', '--list', action='store_true', help='list contacts')
- parser.add_argument('first', help='first name of contact', nargs='?')
- parser.add_argument('last', help='last name of contact', nargs='?')
- parser.add_argument('number', help='phone number of contact', nargs='?')
- args = parser.parse_args()
- # Set attrubutes for a contact
- class Contact:
- def __init__(self, first, last, number):
- self.first = first
- self.last = last
- self.number = number
- def __len__(self):
- global contacts
- return len(contacts)
- def __iter__(self):
- return self
- contacts = []
- def list_contacts():
- try:
- print("Contacts:")
- f = open('c.data', 'rb')
- contacts = pickle.load(f)
- f.close()
- for contact in contacts:
- print(contact)
- print(str(len(contacts)) + " contacts total.")
- if len(contacts) == 0:
- print("No contacts, why don't you add some first?")
- except FileNotFoundError:
- print("No contacts, why don't you add some first?")
- def delete_contact(contact):
- try:
- # load pickle data, remove the contact, reload the data
- f = open('c.data', 'rb')
- contact = pickle.load(f)
- contacts.remove(contact)
- contact = pickle.dump(contact, f)
- f.close()
- num_contacts = len(f.readlines())
- if num_contacts == 0:
- print("No contacts, why don't you add some first?")
- else:
- print("Contact " + args.first +''+ args.last + " deleted")
- except ValueError or FileNotFoundError:
- f = open('c.data', 'rb')
- num_contacts = len(f.readlines())
- if num_contacts == 0:
- print("No contacts, why don't you add some first?")
- def add_contact(contact):
- while True:
- contacts.append(contact)
- f = open('c.data', 'ab')
- pickle.dump(contact, f)
- f.close()
- print("Contact added")
- if args.first and args.last and args.number == None:
- print("No contact entered")
- break
- def Main():
- first = args.first
- last = args.last
- number = args.number
- # The issue is on this line, can't append this as one object
- contact = Contact(first, last, number)
- if args.add and args.first and args.last and args.number:
- add_contact(contact)
- elif args.remove and args.first and args.last and args.number:
- delete_contact(contact)
- elif args.list:
- list_contacts()
- if __name__ == "__main__":
- Main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement