用python读写HDF5格式文件

用python读写HDF5格式文件

    用python读写HDF5格式文件
        HDF5介绍
        创建HDF5文件
        读取HDF5文件
        HDF5的group

用python读写HDF5格式文件
HDF5介绍

       HDF(Hierarchical Data File)是美国国家高级计算应用中心(National Center for Supercomputing Application,NCSA)为了满足各种领域研究需求而研制的一种能高效存储和分发科学数据的新型数据格式 。
       HDF5适合存储大量的二进制信息,并且提供并行IO加快读写速度。
       我们可以用python的h5py包来读写HDF5文件。
创建HDF5文件

    用h5py.File()函数和’w’ 选项创建一个data.h5文件
    如create_dataset() 函数在hdf5文件里面写入dataset,该文件里面有两个dataset分别是dataset_1和dataset_2。
    具体代码如下。

import numpy as np
import h5py
data1 = np.random.random(size = (100,100))
data2 = np.random.random(size = (200,200))
hdfFile = h5py.File('data.h5', 'w')
hdfFile.create_dataset('dataset_1', data=data1)
hdfFile.create_dataset('dataset_2', data=data2)
hdfFile.close()

 
读取HDF5文件

    用h5py.File()函数和’r’ 选项读取一个data.h5文件
    用get() 方法得到某个dataset

hdfFile = h5py.File('data.h5', 'r')
dataset1 = hdfFile.get('dataset_1')
print(dataset1.shape)
hdfFile.close()

HDF5的group

       group在HDF5中的作用类似于linux的文件系统层次结构,通过这个层次结构可以合理的将不同的数据组织起来。

    我们用create_group() 函数创建一个组。
    用keys() 函数来得到HDF5文件里面的group
    用items() 函数可以查看某个group里面的dataset。

hdfFile = h5py.File('data.h5', 'w')
group1 = hdfFile.create_group('group1')
group1.create_dataset('dataset_1', data=data1)
group1.create_dataset('dataset_2', data=data2)
print(hdfFile.keys())

print(group1.items())

 



posted @ 2021-12-02 18:52  锐洋智能  阅读(1123)  评论(0编辑  收藏  举报