0

I have code that makes a folder and places output files in it. I want to use a try-except-else block and an overwrite option, which can be set to True or False, so that in the case where the folder already exists and overwrite is set to false it will just print that the folder already exists, and in all other cases it will just execute without comment.

The only solution I've come up with so far looks like this:

def function( parameters, overwrite = False ):
    try:
        os.makedirs( dir )
    except OSError:
        if overwrite:
            data making code...
        else:
            print dir + ' already exists, skipping...'
    else:
        if overwrite:
            data making code...

Is there maybe a better, or just more elegant solution to this problem? Like, for example, one in which I don't have to duplicate my data making code? Doing it this way reminds me too much of the style in which I've ended up having to write some things in C, and doesn't seem very Pythonic.

tel
  • 13,005
  • 2
  • 44
  • 62

3 Answers3

5

You're pretty close already. Adapting from this answer:

import os, errno

def mkdir(path, overwrite=False):
    try:
        os.makedirs(path)
    except OSError as exc: # Python >2.5
        if exc.errno == errno.EEXIST:
            if not overwrite:
                print "path '%s' already exists" % path   # overwrite == False and we've hit a directory that exists
        else: raise

I don't see why you'd need an else on the try block.

Community
  • 1
  • 1
Daniel DiPaolo
  • 55,313
  • 14
  • 116
  • 115
  • The issue is that, separate from the making of the directory, I need a block of code to execute if 1) overwrite = True or 2) the directory did not exist originally. How would I cover both cases without an else block? – tel Jan 20 '11 at 23:27
  • 3
    @tel: Simply put that after the try/except code. Then put a `return` statement after printing that it already exists. That way, if `os.makedirs` succeeds, or overwrite is True, it will end up writing your output. – Thomas K Jan 20 '11 at 23:58
  • How about `os.path.exists(path)` instead of checking for the `errno`? – Apalala Jan 21 '11 at 00:39
  • +1 for both Daniel DiPaolo and Thomas K. The `else` confused me too, if you simply put the `data making` after the `try` block it does what you want. – Jochen Ritzel Jan 21 '11 at 00:45
  • @thomas k: Ok, I get it now. I see what I was missing. If you put that in an answer I'll accept it. – tel Jan 21 '11 at 02:26
  • @tel: If you insist! @Daniel: I've upvoted your answer, since all I really did was modify it slightly. – Thomas K Jan 21 '11 at 13:16
3

(Building on Daniel DiPaolo's answer)

import os, errno

def mkdir(path, overwrite=False):
    try:
        os.makedirs(path)
    except OSError as exc: # Python >2.5
        if exc.errno == errno.EEXIST:
            if not overwrite:
                print "path '%s' already exists" % path   # overwrite == False and we've hit a directory that exists
                return
        else: raise
    # data making code...
Thomas K
  • 39,200
  • 7
  • 84
  • 86
0
if not os.path.isdir(path):
    os.makedirs(path)
elif not overwrite:
    return # something ?
pass # data making code....

There are reasons why you could want to use makedirs to test for directory existence. In that case:

try:
    os.makedirs( dir )
except OSError:
    if not overwrite:
        print dir + ' already exists, skipping...'
        return
pass # data making code...

You might also want to check if the path exists but is a file and not a directory.

Apalala
  • 9,017
  • 3
  • 30
  • 48