51

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
  • 12,226
  • 19
  • 85
  • 163
Shankar Kumar
  • 1,699
  • 6
  • 21
  • 29
  • 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

90
import os
import shutil

dir = 'path_to_my_folder'
if os.path.exists(dir):
    shutil.rmtree(dir)
os.makedirs(dir)
Ted Klein Bergman
  • 7,245
  • 3
  • 20
  • 40
inspectorG4dget
  • 97,394
  • 22
  • 128
  • 222
25
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
  • 7,245
  • 3
  • 20
  • 40
cybertextron
  • 9,225
  • 24
  • 86
  • 187
  • This also works.. But is this a fairly common module? This code needs to be implemented on many machines.. – Shankar Kumar Jul 26 '12 at 00:36
  • @ShankarKumar Yes. `shutil` is part of `Python`'s built in libraries since `Python 2.4`. I personally think `shutil` is better than `os` due some simplifications it does bring in. – cybertextron Jul 26 '12 at 01:16
6

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
  • 2,592
  • 16
  • 25
2
try:
    os.mkdir(path)
except FileExistsError:
    pass
icanxy
  • 21
  • 2
1

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
  • 12,226
  • 19
  • 85
  • 163
ghostbust555
  • 1,930
  • 14
  • 27
1

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
  • 7,245
  • 3
  • 20
  • 40
El Ruso
  • 8,590
  • 3
  • 26
  • 46
  • 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
  • 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