How to display messages when creating directories?

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 the functionality goes, and if the directory exists, a message appears on the screen, however I cannot get the message returned on the screen when os.makedirs actually creates a nonexistent directory, and I would like code for that.

I used Google and Stackoverflow and came across many, many examples that relate to os.makdir, but did not find one that solves my problem, which is similar but not the same as Check, 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
+4
source share
3

else . "" , OSError dirmk .

, "" , 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

, . Pythonic, - : fooobar.com/questions/1587481/...

+6

, . try , except, OSError... . Creating....

:

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!"
+3

, :

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 state.

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

An alternative is to use try/except/else.

Update: Of course, I can understand why you can use it try/except/elsehere, but IHMO you call os.makedirs()regardless of whether the path exists or not. So I would do this as an improvement for 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 it were written as a reuse function, you could short-circuit this:

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)
+1
source

All Articles