今天爱分享给大家带来hdf5文件格式如何使用【详细教程】,希望能够帮助到大家。
最近,在使用gprMax进行仿真时发现gprMax在进行创建目标的可以从hdf5文件导入对象。而且我发现其实gpeMax的out其实也是hdf5文件格式,但是我竟然不知道hdf5文件是啥东西,有必要系统的了解一下。
hdf5文件结构
HDF5 文件一般以 .h5 或者 .hdf5 作为后缀名,需要专门的软件才能打开预览文件的内容。HDF5 文件结构中有 2 primary objects: Groups 和 Datasets。
Groups 就类似于文件夹,每个 HDF5 文件其实就是根目录 (root) group’/’。
Datasets 类似于 NumPy 中的数组 array 。
+-- / | +-- group_1 | | +-- dataset_1_1 | | | +-- attribute_1_1_1 | | | +-- attribute_1_1_2 | | | +-- ... | | | | | +-- dataset_1_2 | | | +-- attribute_1_2_1 | | | +-- attribute_1_2_2 | | | +-- ... |
整个hdf5文件如上图所示,可以看到group类似我们所熟知的文件夹,dataset就类似于一个numpy中的的array。
每个 dataset 可以分成两部分: 原始数据 (raw) data values 和 元数据 metadata (a set of data that describes and gives information about other data => raw data)。
+-- Dataset
| +-- (Raw) Data Values (eg: a 4 x 5 x 6 matrix)
| +-- Metadata
| | +-- Dataspace (eg: Rank = 3, Dimensions = {4, 5, 6})
| | +-- Datatype (eg: Integer)
| | +-- Properties (eg: Chuncked, Compressed)
| | +-- Attributes (eg: attr1 = 32.4, attr2 = "hello", ...)
|
从上面的结构中可以看出:
Dataspace 给出原始数据的秩 (Rank) 和维度 (dimension)
Datatype 给出数据类型
Properties 说明该 dataset 的分块储存以及压缩情况
Attributes 为该 dataset 的其他自定义属性
python中使用h5py使用hdf5文件
首先安装h5py包,使用 pip install h5py
1.创建一个hdf5文件
#创建一个测试的hdf5文件
import h5py
import numpy as np
f = h5py.File("h5py_exaple.hdf5",'w')
#在该文件下建立一个group
g1 = f.create_group("gro1")
#在g1 group 下建立一个dataset
g1.create_dataset("data1",np.arange(10),np.int16))
g1.reate_dataset("d2",np.arange(10),np.int16))
g1.reate_dataset("d3",np.arange(10),np.int16))
print([key for key in g1.keys()])
#output: ['d2', 'd3', 'data1']
f.close()
2.读hdf5文件
import numpy as np
import h5py
f = h5py.File("h5py_exaple.hdf5","r")
print(f.filename)
#output: h5py_exaple.hdf5
print([key for key in f.keys()])
#output: ['gro1']
print([key for key in f['gro1'].keys()])
#output: ['d2', 'd3', 'data1']
3.追加内容
import numpy as np
import h5py
f = h5py.File("h5py_exaple.hdf5","a")
f.create_group('gro2')
print([key for key in f.keys()])
#output: ['gro1','gro2']
4.删除hdf5文件中的某一个数据集(必须以’w’或者’a’模式打开)
import h5py
with h5py.File("h5py_exaple.hdf5","a") as f:
del f['gro1/data1']
print([key for key in f['gro1'].keys()])
#output ['d2','d3']

![绝对服从危机 絶対服従クライシス v1.0.5 AI汉化 [800M] [日式RPG/动态/背德/PC]](/wp-content/uploads/replace/2025/07/19/5032ab5d3b103be3b35e2eaa34410cb8.webp)