DTek
DTek

Reputation: 371

How can I save all information of a python class to binary?

I'm creating a little shell app to help me save some info and review some python.

I have a couple of python code for a bunch of classes that refer to each other, such as User, Person, Contact, Event and then a main App.py that I use to test it.

I'm using pickle to save the data, using this question as inspiration.

My problem is although the class is saved, it's "internal information isn't".

import Event
import Contact
import pickle
def saveObj(filename, obj):
    with open(filename, 'wb') as output:
    pickle.dump(obj,output, pickle.HIGHEST_PROTOCOL)
    print("SAVED")

def loadObj(filename, obj):
    with open(filename, 'rb') as input:
    obj = pickle.load(input)
    print("LOADED")

p1 = Person.Person("abcd",12,"ui")
p2 = Person.Person("Hah",123,"aaa")
c1 = Contact.Contact([p1,p2], "Wakanda", "12-23-54")
e1 = Event.Event([p1],"12-32-31")
e1.setTitle();
e1.setDescription();

c2 = Contact.Contact([p2],"Forever", "12-23-53")


print("1 for new user, 2 for existing user")
ipt = input("Write something but not exit!\n>>")
filename = ""
while (ipt!= "exit!"):
    if (ipt=="1"):
        print("1")
        idNumber = input("Insert id\n>> ")
        name = input("Inser name\n>> ")
        filename = str(idNumber)+".data"
        session = LoggedIn.User(idNumber,name)
        session.addStuff([e1],[c1,c2],[p1,p2])
        print(session.people)
        saveObj(filename,session)
        del session
    elif(ipt=="2"):
        print("2")
        session = LoggedIn.User(None,None)    
        loadObj(filename,session)
        print(session.people)
    ipt = input("Write something but not exit!\n>>")

The return I'd like would be equal to when I use option 1 and option 2. But instead it's like this:

1 for new user, 2 for existing user
Write something but not exit!
>>1
1
Insert id
>> 12345678
Inser name
>> AAA
[<Person.Person object at 0x7fa8079c6908>, <Person.Person object at 0x7fa8079c6940>]
SAVED
Write something but not exit!
>>2
2
LOADED
[]
Write something but not exit!
>>

How can I fix this?

Upvotes: 0

Views: 110

Answers (1)

Kevin
Kevin

Reputation: 76194

obj = pickle.load(input) doesn't change the value of the object you passed in via the obj parameter. Try using return.

def loadObj(filename):
    with open(filename, 'rb') as input:
        obj = pickle.load(input)
    print("LOADED")
    return obj

#later...

print("2")
session = loadObj(filename)
print(session.people)

Upvotes: 1

Related Questions