如何使用低级Python API关闭HDF5?

2024-10-01 02:31:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我能够修改HDF5文件的缓存设置,方法是将高级和低级pythonh5pyapi结合在下面的堆栈溢出问题中定义:How to set cache settings while using h5py high level interface?

当我试图重命名h5文件时,我得到一个错误消息,说h5文件仍处于打开状态。在HDF5写入操作完成并刷新文件之后,带有contextlib的Python“with”语句似乎没有关闭文件。如何确保使用低级或高级API关闭文件?你能举个例子吗?在

import h5py
import contextlib
import os

filename = 'foo_2.h5'
propfaid = h5py.h5p.create(h5py.h5p.FILE_ACCESS)
settings = list(propfaid.get_cache())
settings[2] *= 5
propfaid.set_cache(*settings)

with h5py.File(filename, 'w') as hf:
    print 'file created'

with contextlib.closing(h5py.h5f.open(filename, fapl=propfaid)) as fid:

    f = h5py.File(fid)
    f.flush()

    # f.close() Seems to be working only in Python 3.4.3 but not in 2.7.7
    #and the "with contextlib.closing(...)  does not work on either version
    f.close()

os.rename(filename, 'foo_2.h5')

其他信息:
操作系统:Windows
Python:2.7.7
水蟒分布:2.0.1
H5py版本:2.3.0


Tags: 文件toimportcachesettingsfoooswith
1条回答
网友
1楼 · 发布于 2024-10-01 02:31:19

我想你在找。close()

f.close()

虽然仔细看,我不知道为什么contextlib.关闭(……)没用。在

我将涉及contextlib的行编辑为:

^{pr2}$

并被移除

f = h5py.File(fid)

之后,我可以检查fid是否已关闭,重命名文件是否按预期工作。在

print fid
<Closed HDF5 file>

os.rename(filename, 'foo2.hdf5')

没有错误,检查目录会显示新名称

相关问题 更多 >