【问题标题】:Can't access returned h5py object instance无法访问返回的 h5py 对象实例
【发布时间】:2016-08-07 16:57:52
【问题描述】:

我有一个非常奇怪的问题。我有 2 个函数:一个读取使用 h5py 创建的 HDF5 文件,另一个创建一个新的 HDF5 文件,该文件连接前一个函数返回的内容。

def read_file(filename):
    with h5py.File(filename+".hdf5",'r') as hf:

        group1 = hf.get('group1')
        group1 = hf.get('group2')            
        dataset1 = hf.get('dataset1')
        dataset2 = hf.get('dataset2')
        print group1.attrs['w'] # Works here

        return dataset1, dataset2, group1, group1

还有创建文件功能

def create_chunk(start_index, end_index):

    for i in range(start_index, end_index):
        if i == start_index:
            mergedhf = h5py.File("output.hdf5",'w')
            mergedhf.create_dataset("dataset1",dtype='float64')
            mergedhf.create_dataset("dataset2",dtype='float64')

            g1 = mergedhf.create_group('group1')
            g2 = mergedhf.create_group('group2')

    rd1,rd2,rg1,rg2 = read_file(filename)

    print rg1.attrs['w'] #gives me <Closed HDF5 group> message

    g1.attrs['w'] = "content"
    g1.attrs['x'] = "content"
    g2.attrs['y'] = "content"
    g2.attrs['z'] = "content"
    print g1.attrs['w'] # Works Here
return mergedhf.get('dataset1'), mergedhf.get('dataset2'), g1, g2

def calling_function():
    wd1, wd2, wg1, wg2 = create_chunk(start_index, end_index)
    print wg1.attrs['w'] #Works here as well

现在的问题是,我可以访问由 wd1、wd2、wg1 和 wg2 创建和表示的新文件中的数据集和属性,并且我可以访问属性数据,但我不能这样做读取并返回值。

当我返回对调用函数的引用后,谁能帮我获取数据集和组的值?

【问题讨论】:

    标签: python python-2.7 hdf5 h5py


    【解决方案1】:

    问题出在read_file,这一行:

    with h5py.File(filename+".hdf5",'r') as hf:
    

    这会在with 块的末尾关闭hf,即当read_file 返回时。发生这种情况时,数据集和组也会关闭,您将无法再访问它们。

    有(至少)两种方法可以解决这个问题。首先,你可以像create_chunk一样打开文件:

    hf = h5py.File(filename+".hdf5", 'r')
    

    并在关闭之前保留对hf 的引用,直到您需要它为止:

    hf.close()
    

    另一种方法是从read_file 中的数据集中复制数据并返回:

    dataset1 = hf.get('dataset1')[:]
    dataset2 = hf.get('dataset2')[:]
    

    请注意,您不能对组执行此操作。只要您需要对组进行操作,文件就需要打开。

    【讨论】:

    • 非常感谢,对 python 比较陌生,所以不知道“with”在做什么。我已经通过复制它来获取数据集内容,但是这些组正在制造所有麻烦。还有一个问题,如果我不使用 hf.close() 关闭文件引用,下次我读取文件时会自动覆盖或关闭它吗?
    • 我的理解是不确定。例如,在调用 hf.close() 之前,数据可能不会真正被写入。
    • 强制写入我正在使用 hf.flush() 的数据,所以我希望没有突然的行为,但感谢您的响应。
    猜你喜欢
    • 1970-01-01
    • 2023-02-06
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多