How to avoid “WindowsError: [Error 5] Access is denied”

后端 未结 7 1771
遥遥无期
遥遥无期 2020-12-06 05:12

There\'s the script to re-create folder:

# Remove folder (if exists) with all files
if os.path.isdir(str(os.path.realpath(\'..\') + \"\\\\my_folder\")):
             


        
相关标签:
7条回答
  • 2020-12-06 05:37

    See RemoveDirectory documentation; "The RemoveDirectory function marks a directory for deletion on close. Therefore, the directory is not removed until the last handle to the directory is closed."

    This means that if something manages to create a handle to the directory you remove (between creation and removal) then the directory isn't actually removed and you get your 'Access Denied',

    To solve this rename the directory you want to remove before removing it.

    So

    while True:
      mkdir('folder 1')
      rmdir('folder 1')
    

    can fail, solve with;

    while True:
      mkdir('folder 1')
      new_name = str(uuid4())
      rename('folder 1', new_name)
      rmdir(new_name)
    
    0 讨论(0)
提交回复
热议问题