Search code examples
pythonpython-3.xpickleshelve

Store many variables in a file


I'm trying to store many variables in a file. I've tried JSON, pickle and shelve but they all seem to only take one variable

import shelve
myShelve = shelve.open('my.shelve')
myShelve.update(aasd,
    basd,
    casd,
    dasd,
    easd,
    fasd,
    gasd,
    hasd,
    iasd,
    jasd)
myShelve.close()

And pickle

import pickle
with open("vars.txt", "wb") as File:
    pickle.dumps(aasd,
        basd,
        casd,
        dasd,
        easd,
        fasd,
        gasd,
        hasd,
        iasd,
        jasd,
        File)

The errors I'm getting are along the lines of

TypeError: update() takes at most 2 positional arguments (11 given)

and

TypeError: pickle.dumps() takes at most 2 positional argument (11 given)

I'm not sure if there's any other way of storing variables except using a database, but that's a bit over what I'm currently capable of I'd say.


Solution

  • You can only pickle one variable at a time, but it can be a dict or other Python object. You could store your many variables in one object and pickle that object.

    import pickle
    
    class Box:
        pass
    
    vars = Box()
    
    vars.x = 1
    vars.y = 2
    vars.z = 3
    
    with open("save_vars.pickle", "wb") as f:
        f.write(pickle.dumps(vars))
    
    with open("save_vars.pickle", "rb") as f:
        v = pickle.load(f)
    
    assert vars.__dict__ == v.__dict__