[GIS] Python scripting for feature classes (loop, sort, merge, and replace)

arcgis-10.1arcgis-desktoparcpymergesorting

This is what I have to accomplish using a python script for ArcGIS 10.1:

  1. Loop through all feature classes and first add a field, then write the name of the feature class into the added field.
  2. Merge all the feature classes from 1. into one feature class called OSRS_ORN_NER.
  3. Sort this feature class by HWY_NUM and replace OSRS_ORN_NER by the sorted one.

This is the code I have for that so far:enter image description here

I think the first part of code is right, but I don't know if I did the second right or if I'm even on the right track for the last part. Also, how exactly would I run a python script in ArcGIS? Any help would be great!

code:

import arcpy, os

arcpy.env.workspace = r'W:\S&P\s&p techs\Emily\TownshipsDissolved\FinalDissolved.gdb'

# Looping through dissolved feature classes, adding 'Name' field and writing
# feature class name in the added field.

for fc in arcpy.ListFeatureClasses():
  arcpy.AddField_management(fc, "Name", "TEXT", field_length = 50)
  with arcpy.da.UpdateCursor(fc, "Name") as cursor:
    for row in cursor:
      row[0] = fc
      cursor.updateRow(row)

# Merging the multiple feature classes into one named OSRS_ORN_NER

list = []

for r in row:
  list.append(r)

arcpy.Merge_management(list, "W:\S&P\s&p techs\Emily\TownshipsDissolved\FinalDissolved.gdb\OSRS_ORN_NER")


# Sorting by HWY_NUM_PR and replacing OSRS_ORN_NER by the sorted feature class 

Sort_management("OSRS_ORN_NER", "OSRS_ORN_NER_new", [["HWY_NUM_PR", "ASCENDING"]])

Best Answer

You need to first assign the ListFeatureClasses() to a variable so you can call it later for the merge

import arcpy, os

arcpy.env.workspace = r'W:\S&P\s&p techs\Emily\TownshipsDissolved\FinalDissolved.gdb'

fcs = arcpy.ListFeatureClasses()

for fc in fcs:
    arcpy.AddField_management(fc, "Name", "TEXT", field_length = 50)
    with arcpy.da.UpdateCursor(fc, "Name") as cursor:
        for row in cursor:
            row[0] = fc
            cursor.updateRow(row)

mergeOutput = r"W:\S&P\s&p techs\Emily\TownshipsDissolved\FinalDissolved.gdb\OSRS_ORN_NER"
sortOutput = r"W:\S&P\s&p techs\Emily\TownshipsDissolved\FinalDissolved.gdb\OSRS_ORN_NER_new"

arcpy.Merge_management(fcs, mergeOutput)
arcpy.Sort_management(mergeOutput, sortOutput, [["HWY_NUM_PR", "ASCENDING"]])
Related Question