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

Shankar Kumar picture Shankar Kumar · Jul 26, 2012 · Viewed 63.1k times · Source

The following code allows me to create a directory if it does not already exist.

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

The folder will be used by a program to write text files into that folder. But I want to start with a brand new, empty folder next time my program opens up.

Is there a way to overwrite the folder (and create a new one, with the same name) if it already exists?

Answer

inspectorG4dget picture inspectorG4dget · Jul 26, 2012
import os
import shutil

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