How to overwrite a folder if it already exists when creating it with makedirs?

import os
import shutil

dir = 'path_to_my_folder'
if os.path.exists(dir):
    shutil.rmtree(dir)
os.makedirs(dir)

import os
import shutil

path = 'path_to_my_folder'
if not os.path.exists(path):
    os.makedirs(path)
else:
    shutil.rmtree(path)           # Removes all the subdirectories!
    os.makedirs(path)

How about that? Take a look at shutil's Python library!


os.path.exists(dir) check is recommended but can be avoided by using ignore_errors

dir = 'path_to_my_folder'
shutil.rmtree(dir, ignore_errors=True)
os.makedirs(dir)