【发布时间】:2017-02-20 15:24:44
【问题描述】:
我能够通过结合以下堆栈溢出问题中定义的高级和低级 Python h5py API 来修改 HDF5 文件的缓存设置:How to set cache settings while using h5py high level interface?
当我尝试重命名文件时,我收到一条错误消息,提示 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
Anaconda 发行版:2.0.1
H5py版本:2.3.0
【问题讨论】:
-
确切的错误信息是什么?
-
WindowsError: [错误 32] 该进程无法访问该文件,因为它正被另一个进程使用
-
如果在代码中的其他位置打开文件(但未关闭),您可能会收到此错误。或者,如果某个其他进程(例如 virus checker or some other application 已打开文件。)您可以尝试使用 Unlocker or Process Explorer 查看哪些应用程序已打开文件。我在您发布的代码中没有看到任何错误。它本身不会引发错误(至少对于我在 linux 上不会)。
-
我添加了一个用于测试的工作脚本。你的 linux 机器上运行的是哪个版本的 Python?