Click here to Skip to main content
15,891,423 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi I cannot work out why my code does not work. How do I make my program to display what has been saved to a file?

Code


Python
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:
    with open ("NewList.pickle", "ab") as file1:
        user = input("Do you want to add contact? (Y/N)")
        if user == "Y" or user == "y":
            print ("works")
            contacts.append(addContact())
            pickle.dump(contacts, file1)
            file1.close()
        else:
            print ("111")
            cont = 0

useropen = input("open file? (Y/N)")
if useropen == "Y" or useropen == "y":
    with open ("NewList.pickle", "rb") as file1:
        conatacts = pickle.load(file1)
        try:
            while True:
                contacts.append(pickle.load(file1))
        except EOFError:
                pass
else:
    print ("null")
Posted
Comments
Sergey Alexandrovich Kryukov 19-Jun-14 20:33pm    
Sorry, the question doesn't make sense unless you explain what do you want to achieve (and what is that "pickling").
—SA
Member 10895549 20-Jun-14 2:54am    
I want to be able to save contacts in the file and later retrieve them. I have problem with loading a file, which means I cannot check if saving into that file works in my code
Aclauring 15-Jul-14 5:24am    
I have found some problems with you code. But I don't know whether this will help you since your code is quite confusing.

1. You have a typo "conatacts" in your code at line -8.
2. You'd better use raw_input so you don't have to wrap your input inside quotes when typing in Person information.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900