Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display messages while 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 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
like image 520
user1995458 Avatar asked Dec 20 '22 04:12

user1995458


1 Answers

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

like image 116
Jomel Imperio Avatar answered Dec 21 '22 16:12

Jomel Imperio