开发者

Getting integers from a tuple saved then loaded with pickle

On Python, I made a module for saving and loading integers, It can save roughly as I want it (I am using Pickle) but when I load it I receive my integers in tuple-form (because I made it a tuple to save) I want to assign the components of the tuple to the integers in my program, but it won't please help! Here is my code:

def save(ob1,ob2,ob3,ob4,ob5):
    import pickle
    tmp = ob1,ob2,ob3,ob4,ob5
    output = open('save.sav','w')
    pickle.dump(tmp,output)
    output.close()

def load(ob1,ob2,ob3,ob4,ob5):
    import pickle
    input2 = open('save.sav','r')
    pickleload = pickle.load(input2)
    ob1 = pickleload[0]
    ob2 = pickleload[1]
    ob3 = pickleload[2]
    ob4 = pickleload[3]
    ob5 = pickleload[4]

I tried to do what aix said, but it didn't work. I am probably putting his code in the wrong places or something like that. Aix, could you please explain this better, or repost my code but edited? Or c开发者_Python百科an someone else help me?


Change load() like so:

def load():
    import pickle
    input2 = open('save.sav','r')
    return pickle.load(input2)

Then it can be used like so:

ob1, ob2, ob3, ob4, ob5 = load()

Your original version doesn't work because when you assign ob1 = ... inside the function, the change doesn't get propagated to the caller when the function returns (ob1 is an immutable object that gets passed by reference; assigning to it rebinds the reference, but the new reference doesn't get passed back to the caller).


The following Python code snippet should help you. The variables ob1 through ob5 are assigned the result of the pickle.load(open('save.sav', 'r')) The variables are declared global, so they can be accessed outside the def load(): function.

import pickle
def load():
    global ob1, ob2, ob3, ob4, ob5
    ob1, ob2, ob3, ob4, ob5 = pickle.load(open('save.sav', 'r'))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜