方法一
使用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)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
方法二
使用numpy
把字典对象保存成.npy文件
import numpy as np
# Save
dictionary = {'hello':'world'}
np.save('my_file.npy', dictionary)
# Load
read_dictionary1 = np.load('my_file.npy',allow_pickle=True)
print(type(read_dictionary1))
print(read_dictionary1)
read_dictionary2 = np.load('my_file.npy',allow_pickle=True).item()
print(read_dictionary2['hello']) # displays "world"
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
如果不加.item()的话读取到的是原始的np.array数据是不能直接使用的
![]()
把列表对象保存成.npy文件
import numpy as np
# Save
np.save('my_file.npy',[1,2,3,[1,2,3]])
# Load
data = np.load('my_file.npy',allow_pickle=True)
print(data)
print(type(data))
print(list(data))
print(data.tolist())
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
![]()
文章知识点与官方知识档案匹配,可进一步学习相关知识
Python入门技能树进阶语法文件416632 人正在系统学习中
评论记录:
回复评论: