python - Multiple objects in pickle file -
python - Multiple objects in pickle file -
i want able add together multiple objects pickle file , able retrieve later. got point can save objects when loading file, lastly entry loaded. mistake?
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) homecoming newcontact cont = 1 contacts = [] while cont == 1: user = input("do want add together contact? (y/n)") if user == "y" or user == "y": print ("works") contacts.append(addcontact()) file = open("list.pickle", "wb") 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": open ("list.pickle", "rb") pickled_file: contacts = pickle.load(pickled_file) else: print("null")
now seems file empty when i'm trying load it:
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) homecoming newcontact cont = 1 contacts = [] while cont == 1: user = input("do want add together 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": open ("clist.pickle", "rb") pickled_file: contacts = pickle.load(pickled_file) else: print("null")
you opening pickle file mode wb
, truncates (set's file empty before writing new). mode want a
opens appending.
python pickle
Comments
Post a Comment