python create polylines with attributes

4977
2
Jump to solution
07-13-2016 01:50 PM
RachelAlbritton
Occasional Contributor III


I've used the following reference to create polylines, and it works great, but I'm having trouble figuring out how to attach attribute information with the polyline being drawn. In the script below, I want the "ID" value that's in the coordsList to also be an attribute feature for that polyline. 

#Input Variables
table = r"S:\Rachel\Data\Temp_Fiber_Manhole_Data\Python_Test\TubeRoutes_Test.dbf"
outputFC = r"S:\Rachel\Data\Temp_Fiber_Manhole_Data\Python_Test\test_output.shp"
template = r"S:\Rachel\Data\Temp_Fiber_Manhole_Data\Python_Test\test_template.shp"


#Create List of coordinates (ID, X, Y)
coordsList = []
for row in arcpy.SearchCursor(table):
    coordsList.append([row.ID,row.From_XCoor,row.From_YCoor])
    coordsList.append([row.ID,row.To_XCoor,row.To_YCoor])
    del row


cur = None
try:
    # Create the output feature class
    arcpy.CreateFeatureclass_management(os.path.dirname(outputFC),os.path.basename(outputFC), "POLYLINE", template,"","",template)


    # Open an insert cursor for the new feature class
    cur = arcpy.da.InsertCursor(outputFC, ["SHAPE@"])


    # Create an array object needed to create features
    array = arcpy.Array()


    # Initialize a variable for keeping track of a feature's ID.
    ID = -1
    for coords in coordsList: 
        if ID == -1:
            ID = coords[0]


        # Add the point to the feature's array of points
        #If the conduit bank ID  has changed, create a new feature
        if ID != coords[0]:
            cur.insertRow([arcpy.Polyline(array)])
            array.removeAll()
        array.add(arcpy.Point(coords[1], coords[2], ID=coords[0]))
        ID = coords[0]
        
    # Add the last feature
    cur.insertRow([arcpy.Polyline(array)])




except Exception as e:
   print(e)
finally:
    # Cleanup the cursor if necessary
    if cur:
        del cur
        
print "done"
0 Kudos
1 Solution

Accepted Solutions
RachelAlbritton
Occasional Contributor III

Nevermind - I just realized that I can use the XY to Line tool to take care of this issue

View solution in original post

2 Replies
RachelAlbritton
Occasional Contributor III

Nevermind - I just realized that I can use the XY to Line tool to take care of this issue

DarrenWiens2
MVP Honored Contributor

You've found your answer, but in general you can do this by including more fields in your cursor:

with arcpy.da.InsertCursor(outputFC, ["SHAPE@","ID"]) as cursor: # should use 'with' notation
  for row in cursor:
    row[0] = # the geometry value
    row[1] = # the ID value
    cursor.insertRow(row) # write entire row