h5py - 我需要手动关闭 HDF5 文件吗?

标签 h5py

我是否正确理解 HDF5 文件应该像这样手动关闭:

import h5py

file = h5py.File('test.h5', 'r')

...

file.close()

来自文档:“HDF5 文件的工作方式通常类似于标准 Python 文件对象。它们支持 r/w/a 等标准模式,并且不再使用时应关闭 .”。

但我想知道:当脚本终止或file被覆盖时,垃圾收集会引发file.close()吗?

最佳答案

@kcw78 很久以前就在评论中回答了这个问题,但我想我不妨把它写下来,作为其他人达到此目的的快速答案。

正如 @kcw78 所说,当您使用完文件后,您应该通过调用 file.close() 显式关闭文件。根据以前的经验,我可以告诉您,当脚本终止时,h5py 文件通常会正确关闭,但有时文件会损坏(尽管我不确定在“r”中是否会发生这种情况)仅限 ' 模式)。最好不要碰运气!

正如 @kcw78 还建议的那样,如果您想安全的话,使用上下文管理器是一个好方法。无论哪种情况,您都需要小心地在关闭文件之前实际提取所需的数据。

例如

import h5py

with h5py.File('test.h5', 'w') as f:
    f['data'] = [1,2,3]

# Letting the file close and reopening in read only mode for example purposes

with h5py.File('test.h5', 'r') as f:
    dataset = f.get('data')  # get the h5py.Dataset
    data = dataset[:]  # Copy the array into memory 
    print(dataset.shape, data.shape)  # appear to behave the same
    print(dataset[0], data[0])  # appear to behave the same

print(data[0], data.shape)  # Works same as above
print(dataset[0], dataset.shape)  # Raises ValueError: Not a dataset

dataset[0] 此处引发错误,因为 dataset 是 h5py.Dataset 的实例,该实例与 f 关联并已关闭于同时 f 关闭。而 data 只是一个 numpy 数组,仅包含数据集的数据部分(即没有其他属性)。

关于h5py - 我需要手动关闭 HDF5 文件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56149237/

相关文章:

python - h5py hdf5 从组成员中提取属性到列表中

python - 使用h5py(或其他方法)高效保存和加载数据

python - 如何扩展 h5py 以便我可以访问 hdf5 文件中的数据?

python - h5py - 将对象动态写入文件?

python - 将嵌套的 .h5 组读入 numpy 数组

python - 使用 h5py 强制 hdf5 文件的数据类型

python - 如何在没有 Microsoft Visual c++ 14.0 的 Windows 上安装适用于 python 3.6 的 h5py

python - 无法在Python中创建HDF5数据集的引用

python - 在 OS X 上安装 h5py

python - 更新 h5py 数据集