python- 变量区变量保存与加载

方法一

推荐一个很简单又好用的保存python变量区变量的模块:dill
https://pypi.org/project/dill/
使用举例,保存变量区变量到文件:

import dill
dill.dump_session('file_name.pkl')

加载文件内容到变量区

dill.load_session('file_name.pkl')

方法二

如果想保存某个或多个对象(变量),可以使用pickle

import pickle

f = open('store.pckl', 'wb')
pickle.dump(obj, f)
f.close()

f = open('store.pckl', 'rb')
obj = pickle.load(f)
f.close()

如果需要保存多个对象,只需将它们放在一个列表或元组中,例如:

import pickle

# obj0, obj1, obj2 are created here...

# Saving the objects:
with open('objs.pkl', 'w') as f:  # Python 3: open(..., 'wb')
    pickle.dump([obj0, obj1, obj2], f)

# Getting back the objects:
with open('objs.pkl') as f:  # Python 3: open(..., 'rb')
    obj0, obj1, obj2 = pickle.load(f)

你可能感兴趣的:(python)