【问题标题】:PermissionError: [WinError 32] for creating filesPermissionError: [WinError 32] 用于创建文件
【发布时间】:2020-12-04 00:52:12
【问题描述】:

有一段代码如下

try:
    f = h5py.File(filename, 'w-')
except: 
    os.remove(filename)
    f = h5py.File(filename, 'w-')  

运行程序得到与上述代码段相关的错误。我认为这是因为文件没有关闭。 google了一下类似的错误信息,貌似可以解决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 python-3.x h5py


    【解决方案1】:

    首先,在使用之前尝试删除文件。
    如果你不能这样做,请尝试读取文件的内容,删除 File 对象,删除文件然后写入文件。

    如果这不起作用,试试这个:

    with h5py.File(filename, 'w-') as f:
        # This is where you put what you're going to do with f
    # At the end of the with statement, the object gets deleted.
    try:
        os.remove(filename)
    except:
        pass
    

    【讨论】:

      【解决方案2】:

      附带说明,共享代码示例中有些地方不清楚:

      try:
          f = h5py.File(filename, 'w-')
      except: 
          os.remove(filename)
          f = h5py.File(filename, 'w-')  # <- why the error handling code is repeating exactly as the code that just failed to run?
      

      当打开系统资源(如文件)时,会存储有关该资源的信息/状态,这些信息/状态应作为程序的干净行为释放/关闭(例如关闭操作系统的文件句柄)。

      所以在 Python 中

      my_file = open('myfile.txt', 'r')  # getting the resource
      my_file.readlines()  # using the resources
      my_file.close()  # closing the file, releasing system resources
      

      为了更容易做到这一点,一些 API 提供了一个 context manager,可以在 with 块中使用:

      with open('myfile.txt', 'r') as my_file:
         my_file.readlines()
      
      # after the with block, the context manager automatically calls close() when exiting the runtime context
      

      h5pyprovides 这样的 API,所以 h5py.File 实例也可以在 with 块中使用:

      with h5py.File(filename, 'w-') as f:
          pass # do your processing with f
      
      # now after the block, the file is closed
      

      请注意,关闭文件并不意味着删除它。因此,在代码中关闭文件并释放系统资源后,文件将保留在磁盘上,直到被删除。但在许多情况下,这是预期的行为,因为文件是程序的结果。

      如果您想确保文件始终被删除,您可以使用try/finally 块,但请注意,在您的程序运行后,磁盘上不会有任何文件:

      try:
         with f = h5py.File(filename, 'w-'):
             pass # use the file resource
      finally:
         if os.path.exists(filename):
             os.remove(filename)
      

      【讨论】:

      • 谢谢回复,请问h5py.file()中的“w”和“w-”到底有什么区别?
      • 我从来没有使用过h5py,并参考了这个问题的文档。据记载,“w”会截断现有文件(覆盖内容),但如果文件存在,“w-”会失败。阅读文档很有帮助。 docs.h5py.org/en/latest/high/file.html#opening-creating-files
      猜你喜欢
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      • 2018-07-13
      • 2022-06-17
      • 2022-07-27
      • 2022-06-22
      • 2018-04-15
      • 2021-05-07
      相关资源
      最近更新 更多