Select to view content in your preferred language

List feature class for Loop and Add Field, Calculate Field

1007
1
12-13-2011 11:30 AM
AmyReinke
Emerging Contributor
I am trying to automate a process where I have several Feature Classes and I want to perform a Spatial Join to one file.  I then want to create a field and then populate it in the original Feature Class with a field from the joined feature class. 

import arcpy
from arcpy import env
import os

# The workspace environment needs to be set before ListFeatureClasses
#    to identify which workspace the list will be based on
#   
env.workspace = "e:/Project"
out_workspace = "e:/Project/Results"


# Loop through a list of feature classes in the workspace
#
for fc in arcpy.ListFeatureClasses():
    
    output = os.path.join(out_workspace, fc)

 # Spatial Join the FC to the cooresponding pop nbrhd file

    target_features = fc
    join_features = "e:/Project/PopularNeighborhoods"
    out_feature_class = output

    arcpy.SpatialJoin_analysis(target_features, join_features, out_feature_class)

    target_explore = fc

    arcpy.AddField_management(target_explore, "popular_Hood", "Text", 50, "", "", "", "NULLABLE", "NON_REQUIRED")


I know the that calculate portion of the script isn't in there, but I wanted to see if I could get it to create new files with the added field and it isn't working. Any help would be greatly appreciated.
Tags (2)
0 Kudos
1 Reply
KimOllivier
Honored Contributor
Have a much closer look at the help for SpatialJoin.

You will see on the RHS that the input data types must be "Feature Layer" so you have to use MakeFeatureLayer_management() first to make layers from the featureclasses.

PS Avoid using CalculateField in a script, use a cursor. The CalculateField tool just wraps a cursor around the expression, but you lose all control of the calculation. If you use a cursor you can test for unexpected data, such as Null values or zero and take action, print error messages and handle different cases. The expressions are also much easier to write.

Leave CalculateField for Modelbuilder.
0 Kudos