如何使用低级Python API关闭HDF5? [英] How to close an HDF5 using low level Python API?

查看:274
本文介绍了如何使用低级Python API关闭HDF5?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过结合以下堆栈溢出问题中定义的高级和低级Python h5py API,我能够修改HDF5文件的缓存设置:

I was able to modify the cache settings of an HDF5 file by combining both the high and low level Python h5py API as defined in the following Stack Overflow question: How to set cache settings while using h5py high level interface?

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

I am getting an error saying that the h5 file is still open when I try to rename the file. The Python "with" statement with the contextlib does not seem to be closing the file after the HDF5 writing operation is completed and the file is flushed. How can I make sure that the file is closed using either the low-level or high-level API? Could you please provide an example ?

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
Anaconda发行:2.0.1
H5py版本:2.3.0

Additional information:
OS: Windows
Python: 2.7.7
Anaconda Distribution: 2.0.1
H5py version: 2.3.0

推荐答案

我认为您正在寻找.close()

I think you are looking for .close()

f.close()

虽然看起来更近了,但我不确定为什么contextlib.closing(...)无法正常工作.

Although looking closer, I'm not sure why contextlib.closing(...) didn't work.

我将涉及contextlib的行编辑为:

I edited the line involving contextlib to be:

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

并删除

f = h5py.File(fid)

然后,我可以检查fid是否已关闭,并且重命名文件是否按预期进行.

Afterwards, I could check that fid was closed and renaming file worked as expected.

print fid
<Closed HDF5 file>

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

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

No errors and check of directory shows the new name

这篇关于如何使用低级Python API关闭HDF5?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆