4

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"]])
1
  • 1
    Could you please copy and paste your code, so we can troubleshoot it?
    – Aaron
    Jan 19, 2015 at 15:40

2 Answers 2

8

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"]])
1

it looks quite OK, but you should initialize your list before you loop on the fc, and correctly indent appending the fc names to your list

for fc in arcpy.ListFeatureClasses():
    list.append(fc)
    ...
arcpy.Merge_management(list,outputname)
arcpy.Sort_management(outputname, finalname, [["HWY_NUM_PR", "ASCENDING"]])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.