如何用h5py优雅获取HDF5文件根级属性的dtype?
问题:用h5py简洁获取HDF5根属性的数据类型及额外信息
我正尝试用h5py获取现有HDF5文件根级属性的数据类型(dtype),现在有个可行但不够简洁的暴力解法。我需要知道像CHS Data Format是长度9的字符串、Save Point ID是64位浮点型这类信息,方便在代码里做正确转换。目前遍历属性能拿到所需信息,但还要手动解析,另外还想获取HDF5View工具里显示的额外信息。附上我的代码和输出,求更优方案。
现有代码
hf = h5py.File(hdf5_filename, 'r') for k in hf.attrs.keys(): print(k, hf.attrs[k], type(hf.attrs[k]), hf.attrs[k].dtype)
现有输出
CHS Data Format b'Version_1' <class 'numpy.bytes_'> |S9 Grid Name b'SMA' <class 'numpy.bytes_'> |S3 Latitude Units b'deg' <class 'numpy.bytes_'> |S3 Longitude Units b'deg' <class 'numpy.bytes_'> |S3 Project b'USACE_NACCS' <class 'numpy.bytes_'> |S11 Region b'Virginia_to_Maine' <class 'numpy.bytes_'> |S17 Save Point ID 1488.0 <class 'numpy.float64'> float64 Save Point Latitude b'41.811900' <class 'numpy.bytes_'> |S9 Save Point Longitude b'-71.398700' <class 'numpy.bytes_'> |S10 Vertical Datum b'MSL' <class 'numpy.bytes_'> |S3
更优解决方案
1. 直接解析类型信息,避免手动处理
h5py的属性对象自带完整元数据,不用额外解析|S9这类标识。可以通过dtype的kind和itemsize直接提取字符串长度,输出更直观的结果:
import h5py with h5py.File(hdf5_filename, 'r') as hf: for attr_name in hf.attrs: attr_val = hf.attrs[attr_name] dtype = attr_val.dtype # 格式化类型描述 if dtype.kind in ('S', 'U'): type_desc = f"字符串(长度{dtype.itemsize})" else: type_desc = dtype.name # 对齐输出,可读性更强 print(f"{attr_name:<20} | 类型: {type_desc:<18} | 值: {attr_val}")
2. 获取HDF5View风格的详细元数据
如果需要HDF5View显示的存储字节数、属性形状等额外信息,可以直接调用h5py的底层API获取:
import h5py with h5py.File(hdf5_filename, 'r') as hf: for attr_name in hf.attrs: attr_val = hf.attrs[attr_name] dtype = attr_val.dtype attr_id = hf.attrs.get_id(attr_name) # 提取HDF5View展示的核心元数据 storage_size = attr_id.get_storage_size() shape = attr_val.shape # 格式化类型描述 if dtype.kind == 'S': type_str = f"ASCII字符串 (长度{dtype.itemsize})" elif dtype.kind == 'U': type_str = f"Unicode字符串 (长度{dtype.itemsize})" else: type_str = dtype.name # 输出详细信息 print(f"属性名: {attr_name}") print(f" 值: {attr_val}") print(f" 数据类型: {type_str}") print(f" 存储字节数: {storage_size}") print(f" 属性形状: {shape}\n")
3. 简化遍历逻辑
h5py的attrs对象支持直接迭代键值对,不用先调用keys(),代码更简洁:
import h5py with h5py.File(hdf5_filename, 'r') as hf: for name, val in hf.attrs.items(): print(f"{name}: 类型={val.dtype}, 值={val}")
内容的提问来源于stack exchange,提问作者rbmales
相关产品推荐
相关产品推荐

