I'm trying to create a layer for each county (based on a layer of all counties) and join only those census tracts located in that county. However, the result I'm getting is a layer named for each county but has all counties and census tracks.

coFC = r"C:\TenCounties" 
coField = "County_Name" 
censusFC = r"C:CT.shp"

# Get a unique list of the counties
values = [row[0] for row in arcpy.da.SearchCursor(coFC, (coField))]
list_of_counties = set(values)

# Create a feature layer for the Census Tracts
arcpy.MakeFeatureLayer_management(censusFC, "lyr_Census")

for county in list_of_counties:
    print county
    # Create a feature layer that contains just the current county
    newout_name = arcpy.ValidateTableName(county)
    arcpy.MakeFeatureLayer_management(coFC, newout_name, "\"County_Name\" = '{0}'".format(county))
    # Select the census tracts that are located in the current county
    arcpy.SelectLayerByLocation_management("lyr_Census", "INTERSECT",    newout_name)
    #Create a layer for each County
    rcpy.CopyFeatures_management(coFC, "lyr_" + newout_name)
  • 1
    Perhaps look at gis.stackexchange.com/a/27352/115 and adapt for arcpy.da rather than arcpy cursors for another approach, but I think your problem is that you are using CopyFeatures on coFC when it should be "lyr_Census". – PolyGeo Nov 5 '15 at 1:48
  • In CopyFeatures, you are passing the original shapefile, coFC. You probably intend to be using the result from select. Edit: argh! beaten by two seconds. – Paul Nov 5 '15 at 1:48

As mentioned twice in comments, you're using your input feature class as your export. You want to use your selected features instead I'm assuming.


rcpy.CopyFeatures_management(coFC, "lyr_" + newout_name)


arcpy.CopyFeatures_management("lyr_Census", "lyr_" + newout_name)

You're not actually creating a layer here though. You're creating a feature class. If you instead want a .lyr file, use:

arcpy.SaveToLayerFile_management ("lyr_Census", "lyr_" + newout_name + ".lyr")

You'll probably want to set the workspace (arcpy.env.workspace) to the folder or geodatabase you wish your layers or feature classes to be exported to as well.

| improve this answer | |
  • Yea, that's all it was. Thanks PolyGeo, Paul and Emil! – user61828 Nov 7 '15 at 0:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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