I want to create a new directory and remove the old one if it exists. I use the following code:
if os.path.isdir(dir_name):
shutil.rmtree(dir_name)
os.makedirs(dir_name)
It works, if the directory does not exist.
It errors if the directory does exist and the program in run normally. (WindowsError: [Error 5] Access is denied: 'my_directory')
However, it also works if the directory already exists and the program is executed in debug mode line by line. I guess shutil.rmtree()
and makedirs()
need some time in between their calls.
What is the correct code so that it doesn't create an error?