编程语言
首页 > 编程语言> > python 将数据对象存储为文件

python 将数据对象存储为文件

作者:互联网

方法一

使用pickle
把对象保存成.pkl文件

import pickle
def save_obj(obj, name ):
    with open('obj/'+ name + '.pkl', 'wb') as f:
        pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)

def load_obj(name ):
    with open('obj/' + name + '.pkl', 'rb') as f:
        return pickle.load(f)

方法二

使用numpy
把对象保存成.npy文件

import numpy as np

# Save
dictionary = {'hello':'world'}
np.save('my_file.npy', dictionary) 

# Load
read_dictionary = np.load('my_file.npy').item()
print(read_dictionary['hello']) # displays "world"

标签:load,文件,存储,obj,name,dictionary,python,pickle,pkl
来源: https://blog.csdn.net/qq_41554005/article/details/112799877