【问题标题】:How to store file paths and read file paths from hdf5 with h5py?如何使用 h5py 从 hdf5 存储文件路径和读取文件路径?
【发布时间】:2021-07-24 09:02:04
【问题描述】:

我想用 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.x hdf5 h5py


    【解决方案1】:

    创建一个数据集来存储一小部分数据是多余的。属性是为此目的而设计的(有时称为元数据)。下面的例子完成了这个任务。 (我使用您的文件名创建了一个属性以及一些额外的属性来演示浮点数和整数的属性用法。)我将这些属性添加到根级别组。您可以将属性添加到任何组或数据集。)在此处完成详细信息:h5py Attributes

    hdf5filename='test2hdf5.h5'
    hdf5dsetname_origin="entry/origin/filename"
    datastring="/path/to/data/verylong/verylong/verlong/extralong"
        
    with h5py.File(hdf5filename, "w") as h5w:
        h5w.attrs[hdf5dsetname_origin] = datastring
        h5w.attrs['version'] = 1.01
        h5w.attrs['int_attr3'] = 3
    
    with h5py.File(hdf5filename,"r") as h5r:
        for attr in h5r.attrs.keys():
            print(f'{attr} => {h5r.attrs[attr]}')
    

    输出如下所示:

    entry/origin/filename => /path/to/data/verylong/verylong/verlong/extralong
    int_attr3 => 3
    version => 1.01
    

    【讨论】:

    • 您好 Kcw78,感谢您的帮助。我希望可以问一些问题。为什么你不必像我一样解码字符串?
    • 您好 Kcw78,感谢您的帮助。我希望可以问一些问题。为什么你不必像我必须做的那样解码字符串?因为您不将其存储为数据集而是作为属性?更大的数据集将与 create_dataset 一起存储,对吗?我理解正确,我的数据字符串不是根级别,而是您的“版本”键,是吗?感谢您链接 h5py 页面,我只希望它有更多示例。非常感谢。
    • 我在尝试解码您的字符串时遇到错误。我将该行修改为string=h5r["/entry/origin/filename"][()],它运行良好。不知道为什么我们会得到不同的行为。我在 Windows 上运行 Python 3.8.3 和 h5py 2.10.0。我只对标量(整数、浮点数、字符串)使用属性。您可以保存数组,但出于性能原因,它们应该小于 64k。基于hdf5dsetname_origin,您在此路径上创建了一个数据集:/entry/origin/filename,其中entry 是根级别组,origin 是子组,filename 是包含字符串的数据集。
    【解决方案2】:

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

    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)
    

    【讨论】:

      猜你喜欢
      • 2021-10-31
      • 2010-10-14
      • 1970-01-01
      • 1970-01-01
      • 2018-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多