GEOG 485:
GIS Programming and Software Development

Lesson 2 Practice Exercise 5 Solution

PrintPrint

Here's one way you could approach Lesson 2 Practice Exercise 5.

If you're new to programming, I encourage you to try figuring out a solution yourself before studying this solution. Then once you've given it your best shot, study the answer carefully. The video below (6:10) explains the script in more depth. Please note that the video uses the old Python 2 syntax with no parentheses (...) for the print statements. That is the only real difference to the Python 3 solution code you see below though.

#This script clips all feature classes in a file geodatabase

import arcpy

# Create path variables
sourceWorkspace = "C:\\Data\\Lesson2PracticeExercise\\USA.gdb"
targetWorkspace = "C:\\Data\\Lesson2PracticeExercise\\Iowa.gdb"
clipFeature = "C:\\Data\\Lesson2PracticeExercise\\Iowa.gdb\\Iowa"

# Get a list of all feature classes in the USA folder
arcpy.env.workspace = sourceWorkspace
featureClassList = arcpy.ListFeatureClasses()

try:

    # Loop through all USA feature classes
    for featureClass in featureClassList:

        # Construct the output path
        outClipFeatureClass = targetWorkspace + "\\Iowa" + featureClass

        # Perform the clip and report what happened
        arcpy.Clip_analysis(featureClass, clipFeature, outClipFeatureClass)
        arcpy.AddMessage("Wrote clipped file " + outClipFeatureClass + ". ")
        print ("Wrote clipped file " + outClipFeatureClass + ". ")

except:

    # Report if there was an error
    arcpy.AddError("Could not clip feature classes")
    print ("Could not clip feature classes")
    print (arcpy.GetMessages())
    
Click for a transcript of "Explanation of Lesson 2 practice exercise" video. (6:10)

PRESENTER: This video explains the solution to the Lesson 2 practice exercise in which we clip a bunch of feature classes from the USA geo database to the Iowa State boundary.

In line 3, we import the arcpy site package. This is required whenever we work with Esri tools or datasets.

In line 6, 7, & 8, we set up a series of string variables representing the locations on disk that we will work with during this script. Now, if you were going to go ahead and make a script tool out of this, you would eventually want to change these to arcpy.GetParameterAsText as described in the lesson text. However, while you're working on your script in Spyder, you'll want to actually write out the full path so you can test and make sure that your script works. Once you're absolutely certain that your script works, then you can go ahead and insert arcpy.GetParameterAsText and then you can start making the script tool and test out the tool. So I recommend you keep those two parts separate, testing in Spyder first and then making the tool.

In line 6 & 7, we set up the paths to some of the geodatabases will be working with. Line 6 is the USA geodatabase that contains the feature classes that we will clip. In line 7, is the Iowa geodatabase where we will put the output feature classes. Line 8 is the actual click feature, this is our cookie cutter feature that is the state boundary of Iowa.

Now, we've used the term workspace in the line six and seven variable names just to mean a folder or a geodatabase in which we're working. But there is an official workspace for arcpy which is the current folder or geodatabase in which arcpy is looking for items; and so, in line 11, we actually set the arcpy workspace to be the same path that we set up in line 6 which is USA, and when we start listing feature classes, that's going to be the workspace that we look in.

Line 12 is where we called the method to list feature classes and the question is, list feature classes where? And the answer is the workspace that we just set up in line 11, so it's going to default to look in arcpy's workspace for the feature classes it should list. And so, what we get out of this is a variable that we call featureClassList and it is a Python list of all the feature classes in the USA geodatabase. This is great now, because we know how to loop through a list, and we're going to do that here in just a minute.

In line 14, we begin a try block, so we'll try to run all this code from line 14 to 25. If for some reason there's a crash, the code will go down to line 27 and run the except block.

In line 17, we begin a for loop to try to go through each feature class in the list. And we create a new variable in line 17 called featureClass. So we say for featureClass in featureClassList. featureClass is just a name that we come up with for that variable. We could name it anything. In this case, it's pretty intuitive to call it featureClass.

Line 20 is setting up the output path. Now, one of our requirements was to append Iowa at the beginning of the output feature class name, and so we're doing a little bit of string manipulation using the plus sign to make a path. This particular string outClipFeatureClass is going to be created by concatenating the target workspace so— that's what you created up in line 7. So that will always be part of the output path. Then, we're going to explicitly add slash Iowa and then, on to that, we'll tack the name of the feature class that we're currently working with. This type of string concatenation to make a path is something that you will also need to do during your Lesson 2 project.

In line 23, we actually perform the clip by calling arcpy.Clip, and we need to put underscore analysis because we want to specify that we're using the Clip tool that's in the Analysis toolbox. Now, Clip, in this case, has three required parameters: the input feature class to be clipped so that's the current one that we're looping on right now—it was defined up in line 17. So that's the first parameter featureClass. The second parameter there is the clipFeature, and we defined that up in line 8. That's our cookie cutter feature what we'll be clipping all the rest of the feature classes to. And then, the third is the output path, and that's the path we just created back in line 20, and once we have all three of those things, we can run the Clip tool.

In lines 24 and 25, we report what happened, and we use a little bit of string concatenation there as well to make a custom message saying that exactly the path of the clipped file that we created. This will be useful in your project, as well. Now, this is an either/or scenario you would need to call either AddMessage or do a print statement in line 25. I just put both of them in here so you can see how they were both used. If you're going to go ahead and make a script tool out of this, that would go in your toolbox in ArcGIS, then you would use the approach in line 24, AddMessage. If you're just going to run this inside of Spyder, then you would use line 25. If for some reason there were to be a crash in the above code, it would jump down to line 27 and run the except statement, and again we're using the approach of doing either an AddError, this is what you would use if you were making a toolbox, so that's line 30; or if you're just running in Spyder, you can do line 31. And then, line 32 is another print statement you could do out of Spyder. It actually gets the message from the Clip tool. The Esri geoprocessing tools report their own error messages, so if you were to have a problem that happened inside the Clip, you might be able to get it back this way by doing print arcpy.GetMessages.

Source: Sterling Quinn

Notes

  • The code above both prints messages and uses arcpy.AddMessage and arcpy.AddError to add geoprocessing messages. Normally, you would only put one or the other in your script. When you're writing your script in Spyder, use print statements to easily see what's going on. When you make a script tool, take out the print statements and add the arcpy.AddMessage and arcpy.AddError functions, so that your messages will appear in the ArcGIS tool results window.