77

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?

nbro
  • 15,395
  • 32
  • 113
  • 196
Shankar Kumar
  • 2,197
  • 6
  • 25
  • 32
  • 2
    It should be noted, though it may not matter to you, that all of the answers here have race conditions (and while it's not really possible to eliminate them completely as posed, you could do better, by using EAFP). – Julian Jul 26 '12 at 01:07

6 Answers6

127
import os
import shutil

dir = 'path_to_my_folder'
if os.path.exists(dir):
    shutil.rmtree(dir)
os.makedirs(dir)
Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
33
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!

Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
cybertextron
  • 10,547
  • 28
  • 104
  • 208
13

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)
shrishinde
  • 3,219
  • 1
  • 20
  • 31
  • Why ```os.path.exists(dir)``` is recommended? Does ```os.path.exists(dir)``` have any advantages comaring to your method? – Ali_Sh Nov 10 '21 at 22:06
  • @Ali_Sh idiomatic practice in Python “it's easier to ask for forgiveness than permission”. Here ignore_errors does the same. – shrishinde Nov 12 '21 at 04:13
  • @Ali_Sh, ignore_errors ignore all errors, not just missing directory errors. – Sandell0 Nov 24 '21 at 16:47
2

Just say

dir = 'path_to_my_folder'
if not os.path.exists(dir): # if the directory does not exist
    os.makedirs(dir) # make the directory
else: # the directory exists
    #removes all files in a folder
    for the_file in os.listdir(dir):
        file_path = os.path.join(dir, the_file)
        try:
            if os.path.isfile(file_path):
                os.unlink(file_path) # unlink (delete) the file
        except Exception, e:
            print e
nbro
  • 15,395
  • 32
  • 113
  • 196
ghostbust555
  • 2,040
  • 16
  • 29
2

Here's a EAFP (Easier to Ask for Forgiveness than Permission) version:

import errno
import os
from shutil import rmtree
from uuid import uuid4

path = 'path_to_my_folder'
temp_path = os.path.dirname(path)+'/'+str(uuid4())
try:
    os.renames(path, temp_path)
except OSError as exception:
    if exception.errno != errno.ENOENT:
        raise
else:
    rmtree(temp_path)
os.mkdir(path)
Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
El Ruso
  • 14,745
  • 4
  • 31
  • 54
  • 1
    Welcome to Stack overflow! This came to me for review as your first answer. When answering an old question with an accepted answer, it's worth highlighting what you are adding to the existing solutions. In this case - can you explain why you believe that this code is immune to the race conditions? For instance - what happens if a file is written to the directory after the call to glob.iglob() - can you describe a reason why your solution is less subject to race condition? Also: you might think about explaining what EAFP stands for. *NB I've re-posted edited comment due to error in original* – J Richard Snape Feb 22 '15 at 21:01
  • @JRichardSnape Yes, you're right, this code is not immune to the race conditions. The new version, in my opinion, satisfy this requirement – El Ruso Feb 23 '15 at 08:53
  • 1
    I think it would be easier to just do `try: os.mkdir(path) except FileExistsError: shutil.rmtree(path) os.mkdir(path)` – Ted Klein Bergman Aug 24 '19 at 13:30
0
try:
    os.mkdir(path)
except FileExistsError:
    pass
icanxy
  • 17
  • 2