[GIS] Python problems with select by attributes and user input

arcpycensusdensitypopulationselect-by-attribute

I am attempting to create a tool where the user can input a census tract number within the city of Plano (there are 77 tracts) and it ultimately creates a map layout showing the population density. I am having problems using the select tool to copy the inputed tract layer into a new feature class.

It is executing successfully but it keeps copying the original plano_tract layer into a new feature class instead of copying the selected tract that was inputed. Not sure if I needed a where clause in the script or if I could simply just do a select by attribute function.

I was using this thread as reference but it I still getting the same result.

Python Script for Select by Attributes taking user input

I am pretty new to Python and this is a beginner exercise for me.

Here is my script:

import arcpy
import os
from arcpy import env

#set workspace
Workspace = arcpy.GetParameterAsText(0)

env.workspace = r"C:\Users\dallascowboy83\Desktop\project 2\project\project.gdb"
env.overwriteOutput = 1

#set local variables
tracts = arcpy.GetParameterAsText(1)

#ask user for tract to search
tract = raw_input("Please type Tract Number: ")

plano_tract = r"C:\Users\dallascowboy83\Desktop\project 2\project\project.gdb\plano_tract.shp"

plano_tract_lyr = "plano_tract_lyr"

#user selects tract, Select by Attribute tool runs
arcpy.MakeFeatureLayer_management("plano_tract", "plano_tract_lyr")

arcpy.SelectLayerByAttribute_management("plano_tract_lyr", "NEW_SELECTION", "\"Tract_Number\" = "+ tract)

arcpy.CopyFeatures_management("plano_tract", "plano_tract_feat")

#add field
arcpy.AddField_management("plano_tract_feat", "density", "DOUBLE")

#calculate field
arcpy.CalculateField_management("plano_tract_select", "density", "[DP0010001] / [sq_mile_1]", "PYTHON", "")

print "executed successfully"

Best Answer

The Select Layer by Attribute tool applies a selection to a layer. However, your Copy Features tool is copying the entire "plano_tract" dataset, and not the "plano_tract_lyr" layer which has the selection applied. Here's the revised code:

#user selects tract, Select by Attribute tool runs
arcpy.MakeFeatureLayer_management("plano_tract", "plano_tract_lyr")

arcpy.SelectLayerByAttribute_management("plano_tract_lyr", "NEW_SELECTION", "\"Tract_Number\" = "+ tract)

arcpy.CopyFeatures_management("plano_tract_lyr", "plano_tract_feat")

To zoom to selected features and export to JPEG:

#Current map document
mxd = arcpy.mapping.MapDocument("CURRENT")

#Assumes only one data frame
arcpy.mapping.ListDataFrames(mxd)[0].zoomToSelectedFeatures()

#Export 
arcpy.mapping.ExportToJPEG(mxd, "Output.jpg")
Related Question