Search code examples
pythondirectorytext-filesoverwrite

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


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?


Solution

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