I'm trying to create a command line tool for saving contacts with Python using Pickle and Argparse. The parser looks for three arguments when adding a contact, first, last, and number.
I've looked though as many forums and stack overflow questions as possible, none of them really apply to my situation. The program has three options, -a (--add), -rm (--remove), and -l (--list). Three functions handle the arguments, add_contact, remove_contact, list_contacts.
My class looks like this:
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
A single contact should have the attributes first, last, and number. This function lists the contacts:
def list_contacts:
try:
print("Contacts:")
f = open('c.data', 'rb')
contacts = pickle.load(f)
f.close()
for contact in contacts:
print(first+" "+last+": " + number)
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?")
Now, I believe the issue is with my Main() function, where the instance of Contact is called:
def Main():
first = args.first
last = args.last
number = args.number
# The issue:
contact = Contact(first, last, number)
if args.add and first and last and number:
add_contact(contact)
elif args.remove and first and last and number:
delete_contact(contact)
elif args.list:
list_contacts()
I want my program to list the contacts like this:
First Last: Number
First Last: Number
2 contact total.
Instead, if I were to get it working somehow it would run like this:
First
Last
Number
3 contacts total
I want to create an instance of the Contact class with the attributes first, last, and number as one object, and append that to the list of contacts. Instead when I list them, I get this:
Contacts:
Traceback (most recent call last):
File "contacts.py", line 105, in <module>
Main()
File "contacts.py", line 102, in Main
list_contacts()
File "contacts.py", line 50, in list_contacts
for contact in contacts:
TypeError: iter() returned non-iterator of type 'Contact'
If this didn't give you enough context, the whole program can be found here: https://pastebin.com/CqJwPVL2 I'm stuck , the iter function didn't fix this. Please help me! Thank you in advance