AnsweredAssumed Answered

Calculate Field Hellp

Question asked by clclark on Mar 1, 2013
Latest reply on Mar 1, 2013 by clclark
Well I am getting better at python scripting. I have the following code block which works fine until the last process which is titled Calculate SNAP_FLAG field with FID values.

Basically when the rest of the code runs, I end up with a field "FID". Based on this fields values I would like to calculate a field "SNAP_FLAG". If "FID" > -1, then I want SNAP_FLAG to be 1. If "FID" = -1, I would like the corresponding records to have a value of 2 for the "SNAP_FLAG" field.

Even if my code for the calculate field part worked, I know there is a much cleaner way of doing this, perhaps with cursors? But I feel it is just out of my grasp right now, and if someone could help me that would be great. The part of the script I am having troubles with is in Red.

# Import arcpy module
import arcpy, sys, traceback
arcpy.env.overwriteOutput = True
from os import path as p

# Define Workspace directory
arcpy.env.workspace = r"C:\Users\Christopher\Desktop\GISData\PS_Steelhead\Work"
# Create List of all Workspaces (GDB)
    for ws in arcpy.ListWorkspaces("*", "FileGDB"):
        arcpy.env.workspace = ws
        print '\n\nSearching in %s\n\n' %ws
# Define Variables to be used in Near processes      
        NB = p.join(ws, "NB")
        NHD = p.join(ws, "NHD")
        NHD_buf = p.join(ws, "NHD_buffer100")
        NB_ID = p.join(ws, "NB_Identity")
# Add SNAP_FLAG field to NB feature class
        arcpy.AddField_management(NB, 'SNAP_FLAG', 'SHORT')
        print '\n\nAdded SNAP_FLAG field %s\n\n' %NB
# Buffer NHD
        arcpy.Buffer_analysis(NHD, NHD_buf, '100 FEET')
        print '\n\nNHD Buffer output created in %s\n\n' %ws
# Run Identity Process
        arcpy.Identity_analysis(NB, NHD_buf, NB_ID, 'ONLY_FID')
        print '\n\nIdentity Analysis Complete for %s\n\n' %NB
# Calculate SNAP_FLAG field with FID values
arcpy.SelectLayerByAttribute_management(NB_ID, "NEW_SELECTION", '"FID_NHD_buffer100" > -1'
arcpy.CalculateField_management(NB_ID, 'SNAP_FLAG', 1)
arcpy.SelectLayerByAttribute_management(NB_ID, "CLEAR_SELECTION")
arcpy.SelectLayerByAttribute_management(NB_ID, "NEW_SELECTION", '"FID_NHD_buffer100" = -1'
arcpy.CalculateField_management(NB_ID, 'SNAP_FLAG', 2)
arcpy.SelectLayerByAttribute_management(NB_ID, "CLEAR_SELECTION")
print 'SNAP_FLAG Calculated For %s'%NB_ID

    # Get the traceback object
    tb     = sys.exc_info()[2]
    tbinfo = traceback.format_tb(tb)[0]
    pymsg = "PYTHON ERRORS:\nTraceback info:\n%s\nError Info:\n%s\n" % (tbinfo, sys.exc_info()[1])
    msgs  = "ArcPy ERRORS:\n%s\n" % arcpy.GetMessages(2)
    print pymsg
    print msgs