Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving integers within pickle and calling them

Tags:

python

So this is my code, I would like to save the value 'test' to the file so that it can be called to be used when the program is reopened.

import pickle
test = 0

def Save():
     with open('objs.pickle', 'wb') as f:
         pickle.dump(test, f)

def Load():
    with open('objs.pickle', 'rb') as f:
        test = pickle.load(f)

The problem with this code is that when I reopen the program and run in and then type in Load(), it says that 'test' is still equal to 0. (Missing somehting obvious probably)

And so my question is, how could I fix the problem issued in italics?

like image 266
Csarg Avatar asked Sep 02 '25 14:09

Csarg


1 Answers

The global variable test has nothing to do with test inside the function Load(). Change your function to:

def Load():
    with open('objs.pickle', 'rb') as f:
        return pickle.load(f)

Now this function returns the value it reads from the pickle file.

Call it like this:

print(Load())

Side note: By convention functions names are all lowercase in Python. So the function name should be actually load().

EDIT

The whole program in a better style:

import pickle

def save(file_name, obj):
    with open(file_name, 'wb') as fobj:
        pickle.dump(obj, fobj)

def load(file_name):
    with open(file_name, 'rb') as fobj:
        return pickle.load(fobj)

def main():
    test = 0
    file_name = 'objs.pickle'
    save(file_name, test)
    print(load(file_name))

if __name__ == '__main__':
    main()
like image 167
Mike Müller Avatar answered Sep 05 '25 12:09

Mike Müller