python保存变量生成pkl文件

1.使用dill保存当前变量区的全部变量

# 保存变量区变量到文件:

import numpy as np
import dill
 
T='Hiya'
val=[1,2,3]
a = np.zeros([4,5])

dill.dump_session('file_name.pkl') # 以上三个变量全部保存在了pkl文件中

# 读取文件内容到变量区:

import numpy as np
import dill
 
# load the session again
dill.load_session('file_name.pkl')

2.使用pickle保存某个或某些对象(变量)

# 保存单个变量

import pickle

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

# 读取单个变量

import pickle

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)

3.使用sklearn保存变量

from sklearn.externals import joblib、

# 保存x
joblib.dump(x, 'x.pkl') 

# 加载x
x = joblib.load('x.pkl') 

4.dataframe类型的数据保存

samples.to_pickle('samples')
pd.read_pickle('samples')

 

参考教程:

https://blog.csdn.net/lrs1353281004/article/details/81544490?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

https://blog.csdn.net/u012605050/article/details/77940798

https://blog.csdn.net/jining11/article/details/81435899

 

你可能感兴趣的:(python,后端,爬虫,大数据)