json文件转换为pkl
时间: 2023-11-24 18:08:38 浏览: 280
pkl与json文件格式转换
将json文件转换为pkl文件可以通过Python内置的pickle模块实现。首先需要将json文件读取出来,然后将其转化为Python中的dict或者list等数据类型,最后使用pickle.dump()函数将数据写入pkl文件中。读取pkl文件时,使用pickle.load()函数即可将数据读取出来。相比于json文件,pkl文件的读取速度更快,但是由于其协议特定于Python,因此不保证跨语言兼容性。下面是一个将多个json文件转换为pkl文件的示例代码:
```
import pickle
import json
root = '/home/raywit/PycharmProjects/'
with open(root + 'training_xyz.json', 'r') as f:
a = np.array(json.load(f))
with open(root + 'k.json', 'r') as f:
fx = np.array(json.load(f))
with open(root + 'k1.json', 'r') as f:
fy = np.array(json.load(f))
with open(root + 'training_verts.json', 'r') as f:
gt = np.array(json.load(f))
list_data = {'training_xyz': a, 'k': fx, 'k1': fy, 'training_verts': gt}
with open("list_data.pkl", "wb") as fo:
pickle.dump(list_data, fo)
fo.close()
with open("list_data.pkl", "rb") as fo:
A = pickle.load(fo, encoding='bytes')
print(A['k'].shape)
```
阅读全文