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

时间:2019-05-15 12:20:09

标签: h5py

我是否正确理解应该手动关闭HDF5文件?

import h5py

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

...

file.close()

从文档中:“ HDF5文件通常像标准Python文件对象一样工作。它们支持r / w / a等标准模式,并且在不再使用时应将其关闭”。

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

1 个答案:

答案 0 :(得分:1)

@ 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数组,仅包含数据集的数据部分(即没有其他属性)。

相关问题