Whenever I go to load a text file for my program it displays the info in the text file yet when I input the roster function it does not display the text file and show it is available to be modified. Is it something with how I created the text file in the first place or is my coding for loadData not written correctly i think i may be confused on the difference between just setting up a function just to read back the file instead of actually opening the text file to be able to modify it.
dict_member = {}
players = dict_member
class Players:
def __init__(self, name, number, jersey):
self.name = name
self.number = number
self.jersey = jersey
def display(self):
print('Printing current members\n')
for number, player in dict_member.items():
print(player.name + ', ' + player.number + ', ' + player.jersey)
def add(self):
nam = input("Enter Player Name\n ")
numb = input("Enter Player Number\n ")
jers = input("Enter Jersey Number\n ")
dict_member[nam] = Players(nam, numb, jers)
def remove(self, name):
if name in dict_member:
del dict_member[name]
def edit(self, name):
if name in dict_member:
nam = input("Enter Different Name\n")
num = input("Enter New Number\n ")
jers = input("Enter New Jersey Number\n ")
del dict_member[name]
dict_member[name] = Players(nam, num, jers)
else:
print("No such player exists")
def saveData(self):
roster = input("Filename to save: ")
print("Saving data...")
with open(roster, "r+") as rstr:
for number, player in dict_member.items():
rstr.write(player.name + ', ' + player.number + ', ' + player.jersey)
print("Data saved.")
rstr.close()
def loadData(self):
dict_member = {}
roster = input("Filename to load: ")
file = open(roster, "r")
while True:
inLine = file.readline()
if not inLine:
'break'
inLine = inLine[:-1]
name, number, jersey = inLine.split(",")
dict_member[name] = (name, number, jersey)
print("Data Loaded Successfully.")
file.close()
return dict_member
def display_menu():
print("")
print("1. Roster ")
print("2. Add")
print("3. Remove ")
print("4. Edit ")
print("5. Save")
print("6. Load")
print("9. Exit ")
print("")
return int(input("Selection> "))
print("Welcome to the Team Manager")
player_instance = Players(None, None, None)
menu_item = display_menu()
while menu_item != 9:
if menu_item == 1:
player_instance.display()
elif menu_item == 2:
player_instance.add()
elif menu_item == 3:
m = input("Enter Player to Remove\n")
player_instance.remove(m)
elif menu_item == 4:
m = input("Enter Player to Edit\n")
player_instance.edit(m)
elif menu_item == 5:
player_instance.saveData()
elif menu_item == 6:
player_instance.loadData()
menu_item = display_menu()
print("Exiting Program...")
Try this:
def loadData(self):
file = open(input("Filename to load: "), "r")
text = file.read()
file.close()
for line in text:
name, number, jersey = (line.rstrip()).split(',')
dict_member[name] = (name, number, jersey)
print("Data Loaded Successfully.")
return dict_member
def saveData(self, dict_member):
file = open(input("Filename to save: "), "a")
for number, player in dict_member.items():
rstr.write(player.name + ', ' + player.number + ', ' + player.jersey)
print("Data saved.")
file.close()
What I think was the error was you using "break" in string from instead of the command, break (no quotes required). I optimized the code a little so maybe it will work now? If not, what exactly happens? Try debugging as well as checking your file.
you didnt load your data into dict_member before displaying the roster
when you load your data in the loadData function you redefine dict_member
so it will "shadow" the outer dict_member so when the display function is called dict_member will always be empty
so you probably want to remove this line
def loadData(self):
# **remove this line --->** dict_member = {}
roster = input("Filename to load: ")
file = open(roster, "r")
while True:
inLine = file.readline()
if not inLine:
break
inLine = inLine[:-1]
name, number, jersey = inLine.split(",")
dict_member[name] = (name, number, jersey)
print("Data Loaded Successfully.")
file.close()
return dict_member
Related
I've been struggling with my code for a class project and am in need of some help. I am not sure if I need to have a nested dictionary or list of dict or just use class in a list or dict. I've struggled to find the answers and could use some help with my code.
Should I just use list instead or am I thinking of this the right way, having the values stored in a dictionary or nested dict of some kind.
I'm especially at a loss for menu==3 #delete an item because as it is now I can only delete one attribute but what I need is to delete a whole property by property ID if possible
As you can probably tell I'm quite confused by now and would really appreciate any help from more experienced programmers.
inventory = {}
#class & constructor
class Property:
def __init__(self, propertyID, address, city, state, zipcode, squarefeet, modelname, salestatus):
self.propertyID = propertyID
self.address = address
self.city = city
self.state = state
self.zipcode = zipcode
self.modelname = modelname
self.squarefeet = squarefeet + 'Square Feet'
self.salestatus = salestatus
def print_Property(o):
if not isinstance(o, Property):
raise TypeError('print_Property(): requires a Property')
print('The property selected is Property ID: {} located at {} {} {} The Sqare footage is {}, {} model, Current status: {}'. format(o.propertyID,o.addresss, o.city, o.state, o.zipcode, o.squarefeet, o.modelname, o.salestatus))
def main():
print('What would you like to do today?')
print('----------------------------------------')
print('1. Add a new item to the Inventory')
print('2. Update an Existing item in the Inventory')
print('3. Delete an existing item from the Inventory')
print('4. View the current item inventory')
print('5. Print the Inventory to a text file')
print('------------------------------')
while True:
try:
menu = int(input('Type a number 1-5'))
if menu == 1: #Add data
print('Add a new property to the inventory...')
propertyID = input('Enter the property Listing ID:') #User inputting a property ID
inventory['Property ID']= propertyID
address = input('Enter the property address:') #User inputting an address
inventory['Address']= address
city = input('Enter property city:') #User inputting a city
inventory['City']= city
state = input('Enter property state:') #User inputting a state
inventory['State']= state
zipcode = int(input('Enter the property zipcode:')) #User inputting a zipcode
inventory['Zipcode']= zipcode
modelname = input('Enter property model name:') #User inputting a property model name
inventory['Model Name']= modelname
squarefeet = int(input('Enter the sqaure footage of the property:')) #User inputting the sqaure footage for the property
inventory['Square Footage']= squarefeet
salestatus = input('Enter the property status:(Is the home sold, available, or under contract?):') #User inputting the property status
inventory['Current Staus']= salestatus
print('The following properties are in the inventory now:')
print(inventory)
#break
elif menu == 2: #Update data
print('Update an item from the inventory...')
print (inventory)
itemreplace = input("Enter the name of the attribute you wish to replace:")
itemupdate = input("Enter the new information for that attribute now:")
inventory[itemreplace]= itemupdate
print(inventory)
elif menu == 3: #Delete data
print("Which property do you want to delete?")
print(inventory)
itemdel = input("Enter the Property ID of the property to delete.")
if itemdel in inventory:
del inventory[itemdel]
print(inventory)
elif menu == 4: #View data
print(inventory)
elif menu == 5: #Print data
output = open("PropertyData.txt", "w")
for item in inventory:
output.write("%s\n" % item)
print('Text file \'PropertyData.txt\' has been created.')
else:
print('That number is not valid. Please try 1-5.')
except ValueError: #throw an error for anything that is not a number
print('You may only select values 1-5. (ex.: 2)')
if __name__ == '__main__': main()
#Lucas is right. Here is a fully working ( I think :) ) system:
import json
class Property:
def __init__(self, propertyID, address, city, state, zipcode, squarefeet, modelname, salestatus):
self.propertyID = propertyID
self.address = address
self.city = city
self.state = state
self.zipcode = zipcode
self.modelname = modelname
self.squarefeet = squarefeet
self._sqfeet_description = str(squarefeet) + ' Square Feet'
self.salestatus = salestatus
def __str__(self):
o = self
return 'Property ID: {}. Address: {}, {}, {}, {}. Size: {} sq feet, {} model. Status: {}.'.format(o.propertyID,o.address, o.city, o.state, o.zipcode, o.squarefeet, o.modelname, o.salestatus)
def as_json(self):
return {x:y for x,y in self.__dict__.items() if not x.startswith("_")}
def int_input(prompt, range=None):
while True:
ans = input(prompt)
if not ans.isnumeric():
print("Please enter a valid number")
continue
ans = int(ans)
if range == None:
return ans
if ans not in range:
print(f"Please enter a number between {min(range)} and {max(range)}")
continue
return ans
inventory = []
def main():
print('What would you like to do today?')
print('----------------------------------------')
print('1. Add a new item to the Inventory')
print('2. Update an Existing item in the Inventory')
print('3. Delete an existing item from the Inventory')
print('4. View the current item inventory')
print('5. Print the Inventory to a text file')
print('------------------------------')
while True:
menu = int_input("Choose an option 1-5", range(1,6))
if menu == 1:
# add data
propertyID = input('Enter the property Listing ID:') #User inputting a property ID
address = input('Enter the property address:') #User inputting an address
city = input('Enter property city:') #User inputting a city
state = input('Enter property state:') #User inputting a state
zipcode = int_input('Enter the property zipcode:') #User inputting a zipcode
modelname = input('Enter property model name:') #User inputting a property model name
squarefeet = int_input('Enter the sqaure footage of the property:') #User inputting the sqaure footage for the property
salestatus = input('Enter the property status:(Is the home sold, available, or under contract?):') #User inputting the property status
this_property = Property(
propertyID,
address,
city,
state,
zipcode,
squarefeet,
modelname,
salestatus)
inventory.append(this_property)
print('The following properties are in the inventory now:')
print(*("\t" + str(i) for i in inventory), sep="\n")
print()
elif menu == 2:
# update data
while True:
propertyID = input("Enter the property id: ")
this_property = [x for x in inventory if x.propertyID == propertyID]
if not this_property:
print("That property doesn't exist")
continue
this_property = this_property[0]
break
lookup = {
"propertyID": str,
"address":str,
"city":str,
"state":str,
"zipcode":int,
"modelname":str,
"squarefeet":int,
"salestatus":str
}
while True:
detail_name = input("Enter the detail you wish to change")
if detail_name not in lookup:
print("That detail does not exist")
continue
break
if lookup[detail_name] == int:
new = int_input("Enter the new value:")
else:
new = input("Enter the new value:")
setattr(this_property, detail_name, new)
elif menu == 3:
# delete
while True:
propertyID = input("Enter the property id: ")
this_property = [i for i, x in enumerate(inventory) if x.propertyID == propertyID]
if not this_property:
print("That property doesn't exist")
continue
this_property = this_property[0]
break
del inventory[this_property]
elif menu == 4:
# print inventory
print('The following properties are in the inventory now:')
print(*("\t" + str(i) for i in inventory), sep="\n")
print()
elif menu == 5:
# save
new_inv = [x.as_json() for x in inventory]
with open("output.txt", "w") as f:
json.dump(new_inv, f)
if __name__ == '__main__':
main()
If you want to save your properties and be able to load them again, add this method to Property:
class Property:
...
#classmethod
def from_json(cls, json_code):
c = cls(*(None for _ in range(8)))
for x,y in json_code.items():
setattr(c, x, y)
return c
and this function to the body of your program:
def load_from_file():
with open("output.txt") as f:
for item in json.load(f):
inventory.append(Property.from_json(item))
and then call the function at the start:
if __name__ == '__main__':
load_from_file()
main()
(obviously make sure the file exists before that though - just save [] to output.txt before running the program for the first time)
The easiest solution is to use a list of Property objects, where each element in a list is an individual property. Adding properties to the inventory means creating a new object, filling in all the fields and appending it to the inventory list.
Below is my code for a class I am currently working. The title contains the errors I am receiving. Could someone please assist with my code? (The comment's explain the area of concern. Main Menu functions 5 & 6.)
PART 1 - CLASS ESTABLISHMENT
class MemberClass:
name = ""
phone = 0
number = 0
# Initiator Method
def __init__(self, name, phone, number):
self.name = name
self.phone = phone
self.number = number
# Mutator Method 1
def set_name(self, name):
self.name = name
# Mutator Method 2
def set_phone(self, phone):
self.phone = phone
# Mutator Method 3
def set_number(self, number):
self.number = number
# Accessor Method 1
def get_name(self):
return self.name
# Accessor Method 2
def get_phone(self):
return self.phone
# Accessor Method 3
def get_number(self):
return self.number
# Display Method
def display_data(self):
print("")
print("Current Team Member's Information")
print("------------------------------------------------")
print("Member's Name: ", self.name)
print("Member's Phone Number: ", self.phone)
print("Member's Jersey Number: ", self.number)
print("------------------------------------------------")
PART 2 - PROGRAM FUNCTIONS AND DATA
# Create a function for the main menu
def print_menu():
print("===========Main Menu===========")
print("1. Display Current Team Roster.")
print("2. Add Member.")
print("3. Remove Member.")
print("4. Edit Member.")
print("5. Save Progress.")
print("6. Load Current Team Roster")
print("9. Exit Program.\n")
return int(input("Please Enter Your Selection: "))
# Create a function for main menu option 1
def print_members(team_members):
if len(team_members) == 0:
print("No Current Team Members In Memory! Please Add All Team Members.")
else:
for x in team_members.keys():
team_members[x].display_data()
# Create a function for main menu option 2
def add_members(team_members):
new_name = input("Enter New Team Member's Name: ")
new_phone = int(input("Enter New Team Member's Phone Number: "))
new_number = int(input("Enter New Team Member's Jersey Number: "))
team_members[new_name] = MemberClass(new_name, new_phone, new_number)
return team_members
# Create a function for main menu option 3
def remove_members(team_members):
remove_name = input("Enter Existing Team Member's Name to Remove: ")
if remove_name in team_members:
del team_members[remove_name]
print("The Team Member ("+remove_name+") Is No Longer In Our Roster.")
else:
print("The Provided Name ("+remove_name+") Is Not Currently In Our Roster. Please Try Again.")
return team_members
# Create a function for main menu option 4
def edit_members(team_members):
original_name = input("Enter Existing Team Member's Name To Edit: ")
if original_name in team_members:
adjusted_name = input("Enter Existing Team Member's Updated Name: ")
adjusted_phone = int(input("Enter Existing Team Member's Updated Phone Number: "))
adjusted_number = int(input("Enter Existing Team Member's Updated Jersey Number: "))
del team_members[original_name]
team_members[original_name] = MemberClass(adjusted_name, adjusted_phone, adjusted_number)
else:
print("The Provided Name ("+original_name+") Is Not Currently In Our Roster. Please Try Again.")
return team_members
# Create a function for main menu option 5 ***PROBLEM AREA***
def save_members(members, filename):
out_file = open(filename, "wt")
with open(filename, "wt") as out_file:
for name, phone, number in members.items():
out_file.write(name + "," + phone + "," + number + "\n")
# Create a function for main menu option 6 ***PROBLEM AREA***
def load_members(members, filename):
in_file = open(filename, "rt")
with open(filename, "rt") as in_file:
while True:
in_line = in_file.readline()
if not in_line:
break
in_line = in_line[:-1]
name, phone, number = in_line.split(",")
members[name] = phone
PART 3 - PROGRAM ROOT CODE
# Team manager welcome screen, date & time
print("Welcome to San Angelo's Softball Team Roster")
print("This program keeps the most up-to-date information")
print("Today's Date: April 23, 2018")
print("Current Time: 0900\n")
# Create a dictionary named "team_members"
team_members = {}
# Provides Menu Screen
menu_selection = print_menu()
# Create while loop repeating the main menu.
while menu_selection != 9:
if menu_selection == 1:
print_members(team_members)
elif menu_selection == 2:
team_members = add_members(team_members)
elif menu_selection == 3:
team_members = remove_members(team_members)
elif menu_selection == 4:
team_members = edit_members(team_members)
elif menu_selection == 5:
filename = input("Enter Desired Filename: ")
save_members(team_members, filename)
elif menu_selection == 6:
filename = input("Enter Existing Filename: ")
load_members(team_members, filename)
menu_selection = print_menu()
print("Thank You For Updating San Angelo's Softball Team Roster!")
When you iterate a dictionary via dict.items, you may only iterate key / value pairs. Therefore, this line will fail as you are attempting to unpack 3 items when only 2 exist (key & value):
for name, phone, number in members.items():
Instead, what you should do:
for name, myclass in members.items():
phone = myclass.phone
number = myclass.number
This is the function defined in class "Roster"
class Roster:
def __init__(self, name, phone, jersy):
self.name = name
self.phone = phone
self.jersy = jersy
def setName(self, name):
self.name = name
def setPhone(self, phone):
self.phone = phone
def setnumber(self, jersy):
self.number = jersy
def getName(self):
return self.name
def getPhone(self):
return self.phone
def getNumber(self):
return self.jersy
def displayMenu(self):
print ("==========Selection Menu==========")
print ("1. Display the Roster")
print ("2. Add a Player to the Roster")
print ("3. Remove a Player from the Roster")
print ("4. Change a Player Name displayed in the Roster")
print ("5. Load the Roster")
print ("6. Save the Roster")
print ("7. Quit")
print ()
return int (input ("Selection>>> "))
def displayRoster(self):
print ("****Team Roster****")
print ("Player's Name:", self.name)
print ("Player's Telephone number:", self.phone)
print ("Player's Jersey number:", self.jersy)
This is the code:( I understand that you don't have to "Import" a class into itself so there is no Import call)
Players = {}
def addPlayer(Players):
newName = input ("Add a player's Name: ")
newPhone = input ("Phone number: ")
newNumber = input ("Jersey number: ")
Players[newName] = newName, newPhone, newNumber
return Players
def removePlayer(Players):
removeName = input ("What name would you like to remove? ")
if removeName in Players:
del Players[removeName]
else:
print ("Name was not found!")
return Players
def editPlayer(Players):
oldName = input ("What name would you like to change? ")
if oldName in Players:
newName = input ("What is the new name? ")
newPhone = input ("Phone number: ")
newNumber = input ("Jersey number: ")
Players[newName] = newName, newPhone, newNumber
del Players[oldName]
print ("***", oldName, "has been changed to", newName)
else:
print ("Name was not found!")
return Players
def saveRoster(Players):
print("Saving data...")
outFile = open("D:\Documents\Grantham\Python Projects\Python Week Six\Roster.txt", "wt")
for x in Players.keys():
name = Roster.getName(Players)
phone = Roster.getPhone(Players)
jersy = Roster.getNumber(Players)
outFile.write("name+","+phone+","+jersy+","\n")
print("Data saved.")
outFile.close()
return Players
def loadRoster():
Players = {}
filename = input("Filename to load: ")
inFile = open(Filename(Players), "rt")
print("Loading data...")
while True:
inLine = inFile.readline()
if not inLine:
break
inLine = inLine[:-1]
name, phone, jersy = inLine.split(",")
Players[name] = RosterClass.Players(name, phone, jersy)
print("Data Loaded Successfully.")
inFile.close()
return Players
print ("Welcome to the Team Manager")
menuSelection = Roster.displayMenu ('Players')
while menuSelection != 7:
if menuSelection == 1:
myRoster.displayRoster (Players)
elif menuSelection == 2:
Players = addPlayer (Players)
elif menuSelection == 3:
Players = removePlayer (Players)
elif menuSelection == 4:
Players = editPlayer (Players)
elif menuSelection==5:
loadRoster(Players)
elif menuSelection==6:
saveRoster(Players)
menuSelection = Roster.displayMenu (Players)
print ("Exiting Program...")
I keep getting this error:
Traceback (most recent call last):
File ".idea/Adv Team Roster.py", line 108, in <module>
Roster.displayRoster ('Players')
File ".idea/Adv Team Roster.py", line 39, in displayRoster
print ("Player's Name:", self.name)
AttributeError: 'str' object has no attribute 'name'
I'm also having problems with the save/load routine but that's another post.
Your code has a number of conceptual problems that you need to solve before you can start trying to run it and start asking for help with compiler errors. Here are three, to get you started.
(1) Your Roster class is designed to be instantiated, but you never create an instance. Whenever you write a class, among the early questions you should ask yourself are, "What code will create instances of this class? Under what circumstances? How will that code get the data it needs to create an instance? What will that code do with the instance right after it has created the instance?"
(2) Your Roster class is misnamed, which is probably confusing you. A roster is a list of players. Your Roster is data about a single player. I recommend renaming Roster to Player, creating some data structure (like your current Players) called roster to hold a bunch of players, and then following the consequences of that change.
(3) Once you have a clear idea of what rosters and players are, you can ask questions like, "Where will I store rosters and players? How will I pass them around to different parts of my code? What functionality should be associated with a roster? with a player? with the top level of my code? with other entities that I haven't thought about yet?"
After all that thinking, you might come the conclusion that displayPlayer should be a function on the Player class and that you therefore need to rename displayRoster to displayPlayer. Since you will have created instances of Player, perhaps one called myplayer (that's just an example name), you will now be able to say myplayer.displayPlayer(), and Python will run the displayPlayer code with self automatically set to the myplayer instance. At that point the compiler error you are complaining about will disappear, not because you "fixed" it, but because it naturally goes away once you are thinking clearly about your system.
And in general, that is the way to think about compiler errors: If it's not immediately obvious how to fix it, then it's probably a sign that you aren't thinking clearly about your system, so you need to take a step back and think about higher-level problems than the specific error.
I'm doing creating a address book for a computer science class, where we are supposed to have a list of objects "contact" written to a file when the program closes and read from the file when the program starts. However, after the data is written to the file, once it is read it does not seem to keep its object form.
import pickle
class Contact:
#Creating the class with the attributes I want
def __init__(self, firstname, lastname, number, areacode, city):
self.firstname = firstname
self.lastname = lastname
self.number = number
self.areacode = areacode
self.city = city
def __str__(self):
return "({0} {1}, {2}, {3}, {4})".format(self.firstname, self.lastname, self.number, self.areacode, self.city)
#reading the object
def opendata():
readable = []
addresses = []
A = open("Address_book", "rb+")
addresses = A.read()
A.close
B = len(addresses)
if B != 0:
readable = pickle.loads(addresses)
return readable
else:
return addresses
def savedata(file):
addresses = open("Address_book", "wb+")
temp = pickle.dumps(file)
addresses.write(temp)
addresses.close()
def Address_manager():
Address = []
fromfile = opendata()
Address.append(fromfile)
while True:
print("add = add contact, modify = modify contact, search = search contacts, end = close program, print = print full list")
A = input("What do you want to do?: ")
if A == "end":
savedata(Address)
break
else:
if A == "print":
for i in Address:
print(str(i))
print("")
continue
elif A == "add":
Address.append(add_contact())
print("")
continue
elif A == "search":
lists2 = search_contact(Address)
A = 0
for i in lists2:
A += 1
print(A, str(i))
print("")
print("")
continue
elif A == "modify":
modified = modify_contact(Address)
Address.append(modified)
print("")
continue
def add_contact():
while True:
try:
A = Contact(input("First name: "), input("Last name: "), input("Phone Number: "), input("Area Code: "), input("City: "))
print(str(A))
B = input("Is this right?: (y/n)")
if B == "y":
print("Well done?")
return A
else:
print("Try Again")
continue
except:
print("bad data")
If I try to "print" the list after getting it from the file it prints them in the wrong form. What am I doing wrong and why?
Edit 1: I apologize for the less than efficient code.
Edit 2: Added function to add contact
I cannot get my file to store multiple instances of contacts. After adding new contact and trying to print them, it comes up with "IndexError: list index out of range" error. What shall I do to make it work?
import pickle
class People():
def __init__(self, name, surname, age, mobile_no, home_no):
self.name = name
self.surname = surname
self.age = age
self.mobile_no = mobile_no
self.home_no = home_no
def DisplayContacts(self):
print("First Name: \t", self.name)
print("Surname: \t", self.surname)
print("Age: \t", self.age)
print("Mobile Number: \t", self.mobile_no)
print("Home Number: \t", self.home_no)
print()
def addContact():
newname = str(input("First name: \t"))
newsurname = str(input("Surname: \t"))
newage = int(input("Age: \t"))
newmobile_no = int(input("Mobile Number: \t"))
newhome_no = int(input("Home Number: \t"))
newContact = People(newname, newsurname, newage, newmobile_no, newhome_no)
return newContact
cont = 1
contacts = []
while cont == 1:
user = input("Do you want to add contact? (Y/N)")
if user == "Y" or user == "y":
print ("works")
contacts.append(addContact())
file = open("CList.pickle", "ab")
pickle.dump(contacts, file, pickle.HIGHEST_PROTOCOL)
file.close()
else:
print ("111")
cont = 0
useropen = input("open file? (Y/N)")
if useropen == "Y" or useropen == "y":
with open ("CList.pickle", "rb") as pickled_file:
contacts = pickle.load(pickled_file)
print(contacts[0].surname)
print(contacts[1].surname)
else:
print("Null")
Simply appending a picked object to a file is not the same thing as pickling a list. EAch time you append, you've created another pickled record. Read the file multiple times to get your list:
with open ("CList.pickle", "rb") as pickled_file:
contacts = []
try:
while True:
contacts.append(pickle.load(pickled_file))
except EOFError:
pass
Now, instead of appending the list of contacts (which would give you a list of lists with many duplicates), just pickle the new contact:
with open("CList.pickle", "ab") as _file:
while True:
user = input("Do you want to add contact? (Y/N)")
if user == "Y" or user == "y":
print ("works")
pickle.dump(addContact(), _file, pickle.HIGHEST_PROTOCOL)
else:
print ("111")
break