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?
The PermissionError: [errno 13] permission denied error occurs when you try to access a file from Python without having the necessary permissions. To fix this error, use the chmod or chown command to change the permissions of the file so that the right user and/or group can access the file.
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)
Permissions might be the problem, but I had the same problem '[Error 5] Access is denied' on a os.rename()
and a simple retry-loop was able to rename the file after a few retries.
for retry in range(100):
try:
os.rename(src_name,dest_name)
break
except:
print "rename failed, retrying..."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With