Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

python - How to avoid "WindowsError: [Error 5] Access is denied"

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")):
        shutil.rmtree(os.path.realpath('..') + "\my_folder", ignore_errors=True)
# Create new folder
os.mkdir(os.path.realpath('..') + "\my_folder")

This works nearly always, but in some cases (on creation step) I get

WindowsError: [Error 5] Access is denied: 'C:\Path\To\my_folder'

What could cause this error and how can I avoid it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...