我是否正确理解 HDF5 文件应该像这样手动关闭:
import h5py
file = h5py.File('test.h5', 'r')
...
file.close()
文档中:“HDF5 文件的工作方式通常类似于标准 Python 文件对象。它们支持 r/w/a 等标准模式,并且 不再使用时应关闭。”。
但我想知道:当脚本终止或
file.close()
被覆盖时,垃圾收集会引发 file
吗?
@kcw78 很久以前就在评论中回答了这个问题,但我想我不妨将其写下来,作为其他人达到此目的的快速答案。
正如 @kcw78 所说,当您使用完文件后,您应该通过调用 file.close()
显式关闭文件。根据以前的经验,我可以告诉您,当脚本终止时,h5py 文件通常会正确关闭,但有时文件会损坏(尽管我不确定仅在“r”模式下是否会发生这种情况)。最好不要碰运气!
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
数组,仅包含数据集的数据部分(即没有其他属性)。