Monday, February 22, 2010

Fun With Adding Fields

A common process that can be done multiple times during analysis is creating new feature classes. To strealine this process, I have developed a class that can create a feature class and add fields.

1). Create a python class and create the following Enum Classes

code>
class SomeClass:

     def __init__(self, GP):

          self.GP = GP

    class FeatureType:

        POLYGON = "POLYGON"

        POLYLINE = "POLYLINE"

        POINT = "POINT"

    class AddFieldTypesEnum:

        TEXT = "TEXT"

        FLOAT = "FLOAT"

        DOUBLE = "DOUBLE"

        SHORT = "SHORT"

        LONG = "LONG"

        DATE = "DATE"

        BLOB = "BLOB"

        RASTER = "RASTER"


2). Add the following code below the class AddFieldTypesEnum

def CreateFeatureClass(self, workspace="in_memory", fileName="temp", FeatureType=FeatureType.POLYGON, SpatialReference="", Fields=[],overwrite=True):

        gp = self.GP

        if gp.exists(workspace + os.sep + fileName) == True and overwrite == True:

            if gp.overwriteoutput != 1:

                gp.overwriteoutput = 1

            #gp.delete(workspace + os.sep + fileName)

        elif gp.exists(workspace + os.sep + fileName) == True and overwrite == False:

            gp.adderror("Feature with name: " + fileName + " alread exists")

        if SpatialReference == "":

            desc = gp.describe(self.FC)

            SpatialReference = desc.SpatialReference

        gp.createfeatureclass(workspace, fileName, FeatureType, "","","",SpatialReference)

        if len(Fields) > 0:

            for field in Fields:

                gp.addfield(workspace + os.sep + fileName, field[0], str(field[1]))

        return workspace + os.sep + fileName

    



The class is ready to use

Here is a simple example:

import Arcgisscripting as Arc

gp = Arc.create(9.3)
myClass = SomeClass(gp)
myClass.CreateFeatureClass()

print 'dah da'

No comments: