4

I am looking for input to print a message when creating directories. Im in a mixed os environment but in my case using Win 7, python 2.7, ArcGIS 10.2.

The code below works fine as far as functionality goes, and if the directory does exist the message appears on the screen however i cant get a message returned to the screen when os.makedirs is actually creating the non existant directory and i would like the code to do that.

I have used Google and Stackoverflow and come across many, many examples that deal with os.makdir but have not found any that resolve my issue which is similar but not same as Check if Dir Exists

    td = arcpy.env.workspace

    dn1 = "Test" dirmk = td +sep+ dn1

    try:
        os.makedirs(dirmk) except OSError:
        if os.path.exists(dirmk):
            print '\n' + dn1 + " dir already exists so keep on hustlin"
        else:
            print '\n' + "Creating " + dn1
Community
  • 1
  • 1

3 Answers3

6

Your else clause looks like it's out of place. In the code you posted, the "Creating" message would've been printed only when an OSError occurred AND dirmk did not exist.

In this snippet below, the "Created" message would be printed if no errors were encountered while creating dirmk.

td = arcpy.env.workspace

dn1 = "Test"
dirmk = td + sep + dn1

try:
    os.makedirs(dirmk)
except OSError:
    if os.path.exists(dirmk):
        print '\n' + dn1 + " dir already exists so keep on hustlin"
else:
    print '\n' + "Created " + dn1

This is the smallest change to your existing code that would satisfy your use case. But you can make this more concise and Pythonic by doing something similar to the suggestion in another answer: https://stackoverflow.com/a/30180115/460282

Community
  • 1
  • 1
Jomel Imperio
  • 914
  • 4
  • 16
  • Excellent thanks Jomel. that works fine. I also appreciate all the commenst and responses below. Fingers crossed I can get time to explore all the other options below later this week. – user1995458 May 12 '15 at 22:56
3

You're close, but not quite there. In your try block, the only time that you're going to get into the except is if there's an OSError...like the file already exists. So you're never going to see the Creating... message.

This should work better:

import os  # In your original, you weren't importing this.

td = arcpy.env.workspace

dn1 = "Test"
dirmk = td + sep + dn1

try:
    os.makedirs(dirmk)

except OSError, e:
    if e.errno == 17:  # Error code for file exists
        print '\n' + dn1 + " dir already exists so keep on hustlin"
    else:
        print "OSError %s" % e

else:
    print '\n' + "'" + dn1 + "' created!"
Doug R.
  • 3,135
  • 20
  • 46
2

Rearrange your code a bit so it reads:

if not os.path.exists(dirmk):
    print "Creating: {}".format(dirmk)
    os.makedirs(dirmk)
else:
    print "{} already exists; skipping".format(dirmk)

You are already trying to use os.path.exists() so use it in a condition.

If path does not exists; create it and print a message; otherwise skip.

The alternative is to use a try/except/else.

Update: Of course I can see why you might want to use a try/except/else here but IHMO you are calling os.makedirs() regardless of whether the path exists or not. So I would do this as an improvement to catch and OSError(s):

if not os.path.exists(dirmk):
    print "Creating: {}".format(dirmk)
    try:
        os.makedirs(dirmk)
    except:
        print "Failed to create {}".format(dirmk)
else:
    print "{} already exists; skipping".format(dirmk)

And if this were written as a reuseable function you could short-circuit this to just:

def create_if_not_exists(dirmk):
    if os.path.exists(dirmk):
        print "{} already exists; skipping".format(dirmk)  
        return

    print "Creating: {}".format(dirmk)

    try:
        os.makedirs(dirmk)
    except:
        print "Failed to create {}".format(dirmk)
James Mills
  • 17,096
  • 3
  • 41
  • 56
  • It depends on which is the more likely scenario - is the OP more likely to find that the directory does or does not exist? – Doug R. May 12 '15 at 01:24
  • Good question :) But it's generally good practice to short-circuit functions like this anyway for readability (*if nothing else*) :) – James Mills May 12 '15 at 01:26
  • This is true. The more common idiom is certainly `try/except/else`. – Doug R. May 12 '15 at 01:28
  • 1
    I agree; That's why ``try/except/else`` was introduced in the language some time ago :) -- However I personally feel IHMO that "trying" something for the sake of "trying" when a simple test can suffice a bit superfluous :) -- In practice setting up exception handling can be costly depending on what you're doing too. – James Mills May 12 '15 at 01:30