Friday, August 20, 2010

Python Tip: Iterating through a feature class

After you have mastered creating Python scripts to perform geoprocessing tasks on single feature classes, you will probably realize that you will often come across cases where you will want to perform the same tasks on all the features in a feature class, such as adding a field, adding a prefix or suffix to the name, etc.  Accomplishing this is very easy.  You ill need to iterate through a feature class using the ListFeatureClasses function.  I will give you an example that capitalizes the names of the feature classes in a feature class.  Start by importing the proper modules:

import sys, string, os, os.path, arcgisscripting

Next add the toolbox with the Rename tool:

gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")

Set the workspace to the feature class you wish to edit:

gp.workspace = "Database Connections\\GIS.sde\\Data"

Call the ListFeatureClasses function and move to the first feature class:

fcList = gp.ListFeatureClasses ("*", "all")
fc = fcList.Next()

Now loop through and rename each feature class:

while fc <> None:
     gp.Rename_management(gp.workspace + "\\" + fc, 
                          gp.workspace + "\\" + fc.upper() \
                          + "_temp", "FeatureClass")
     gp.Rename_management(gp.workspace + "\\" + fc.upper() \
                          + "_temp",  
                          gp.workspace + "\\" + fc.upper(),
                          "FeatureClass") 

     fc = fcList.Next()

Because ArcGIS is not case-sensitive, we had to temporarily rename the feature classes with "_temp" at the end, and then rename them again and capitalize them.  Also, remember to call the Next function to move to the next record or you will be stuck in an infinite loop.

In this case, we ran through every feature class but using the wild card parameter, you can select a subset of the feature classes.  Other similar functions exist that are also useful such as ListDatasets and ListTables.  I recommend that you read more about these functions here.

No comments:

Post a Comment