有一个代码段如下
try:
f = h5py.File(filename, 'w-')
except:
os.remove(filename)
f = h5py.File(filename, 'w-')
运行程序获取与上述代码段相关的错误。我想是因为文件没有关闭。通过谷歌搜索类似的错误消息,似乎可以解决using "with" statement,但我不确定如何修改上述代码段
OSError Traceback (most recent call last)
<ipython-input-19-1f1f9c5eb3dd> in vid_to_hdf(En, start, end, chunk)
9 try:
---> 10 f = h5py.File(filename, 'w-')
11 except:
~\AppData\Local\Continuum\anaconda3\envs\fastai-py37\lib\site-packages\h5py\_hl\files.py in __init__(self, name, mode, driver, libver, userblock_size, swmr, rdcc_nslots, rdcc_nbytes, rdcc_w0, track_order, **kwds)
407 fapl, fcpl=make_fcpl(track_order=track_order),
--> 408 swmr=swmr)
409
~\AppData\Local\Continuum\anaconda3\envs\fastai-py37\lib\site-packages\h5py\_hl\files.py in make_fid(name, mode, userblock_size, fapl, fcpl, swmr)
176 elif mode in ['w-', 'x']:
--> 177 fid = h5f.create(name, h5f.ACC_EXCL, fapl=fapl, fcpl=fcpl)
178 elif mode == 'w':
h5py\_objects.pyx in h5py._objects.with_phil.wrapper()
h5py\_objects.pyx in h5py._objects.with_phil.wrapper()
h5py\h5f.pyx in h5py.h5f.create()
OSError: Unable to create file (file exists)
During handling of the above exception, another exception occurred:
PermissionError Traceback (most recent call last)
<timed eval> in <module>
<ipython-input-19-1f1f9c5eb3dd> in vid_to_hdf(En, start, end, chunk)
10 f = h5py.File(filename, 'w-')
11 except:
---> 12 os.remove(filename)
13 f = h5py.File(filename, 'w-')
14 # Create dataset within file
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'E23.hdf5'
作为旁注,共享代码示例中有些地方不清楚:
打开系统资源(如文件)时,会存储有关该资源的信息/状态,这些信息/状态应作为程序的干净行为释放/关闭(例如关闭操作系统的文件句柄)
所以在Python中
为了更容易做到这一点,一些API提供了可以在with块中使用的context manager:
h5py
provides这样的API,因此h5py.File
实例也可以在with
块中使用:请注意,关闭文件并不意味着删除它。因此,在代码中关闭文件并释放系统资源后,文件将保留在磁盘上,直到被删除。但在许多情况下,这是预期的行为,因为文件是程序的结果
如果要确保文件始终被删除,可以使用
try/finally
块,但请注意,在程序运行后,磁盘上将不会保留任何文件:首先,请尝试在使用文件之前删除它。
如果您不能这样做,请尝试读取文件内容,删除文件对象,删除文件,然后写入文件
如果不起作用,请尝试以下方法:
相关问题 更多 >
编程相关推荐