首页 > 解决方案 > 如何使用 h5py 从 hdf5 存储文件路径和读取文件路径?

问题描述

我想用 h5py 在我的 hdf5 中将一个很长的文件路径保存为字符串。我有以下代码,但它似乎不起作用。当我读取文件时,变量不显示文件路径。请问怎么做比较好?谢谢你。

import h5py

hdf5filename='testhdf5.h5'
hdf5dsetname_origin="/entry/origin/filename"

# create hdf5 file and store a very long file path

with h5py.File(hdf5filename, "w") as h5f:
    string_dt = h5py.special_dtype(vlen=str)
    h5f.create_dataset(hdf5dsetname_origin, data='/path/to/data/verylong/verylong/verlong/extralong',dtype=string_dt)           

# read it and check the file path

with h5py.File(hdf5filename,"r") as h5:
    string=h5["/entry/origin/filename"]

print(string)

标签: python-3.xhdf5h5py

解决方案


在一些帮助下,我找到了解决方案。

hdf5filename='test2hdf5.h5'
hdf5dsetname_origin="entry/origin/filename"

datastring="/path/to/data/verylong/verylong/verlong/extralong"


with h5py.File(hdf5filename, "w") as h5f:
    string_dt = h5py.special_dtype(vlen=str)
    h5f.create_dataset(hdf5dsetname_origin, data=datastring, dtype=string_dt)

with h5py.File(hdf5filename,"r") as h5:
    print(h5.keys())
    string=h5["/entry/origin/filename"][()].decode('utf-8')
    print(string)

推荐阅读