Manipulating polyline features using ArcPy

Dr. Huidae Cho
Institute for Environmental and Spatial Analysis...University of North Georgia

1   Create polylines

Use the InsertCursor and Polyline to add new polylines.

# create a new shapefile
# arcpy.CreateFeatureclass_management returns a Result object; take the first item, which is the full path
fc = arcpy.CreateFeatureclass_management(r'P:\tmp', 'test_polylines.shp', 'POLYLINE')[0]

# add some fields
arcpy.AddField_management(fc, 'length', 'DOUBLE')

# get the extent of the active map
ext ='CURRENT')

# here we'll insert geometry and length
pnts = []
with arcpy.da.InsertCursor(fc, ['SHAPE@', 'length']) as cur:
  line = arcpy.Polyline(arcpy.Array(pnts))
  cur.insertRow([line, line.length])

  line = arcpy.Polyline(arcpy.Array(pnts))
  cur.insertRow([line, line.length])

2   Update polylines

center = arcpy.Point((ext.lowerLeft.X + ext.upperRight.X) / 2, (ext.lowerLeft.Y + ext.upperRight.Y) / 2)

# retrieve all features for now
with arcpy.da.UpdateCursor(fc, ['SHAPE@', 'length']) as cur:
  for row in cur:
    line = row[0]
    changed = False
    if line[0][0].equals(ext.lowerLeft):
      changed = True
      pnts = [center, line[0][1]]
    elif line[0][1].equals(ext.lowerLeft):
      changed = True
      pnts = [line[0][0], center]
    if changed:
      line = arcpy.Polyline(arcpy.Array(pnts))
      cur.updateRow([line, line.length])