I want to create a tool that allows a user to select all the points within a specific zip code by inputting that zip code. The code below selects ALL of the points with a zip code - which is all of them.

I've tried various iterations of the SQL expression, but this the only one that doesn't cause a crash. Please let me know if you have a solution.

The code below works:

# Author: John K. Tran
# Contact: jtran20@masonlive.gmu.edu
import arcpy
import os
from os import listdir
import csv
print "arcpy imported"

Input CSV can look like:

Lat,Lon,First Name,Last Name

Make sure 'Lat' and 'Lon' fields are the 1st and 2nd column in the CSV respectively.


incsv = arcpy.GetParameterAsText(0)# Change this to the path of your CSV file.
outfc = r'N:\ReferenceMaterials\ArcGIS Python\Pavement Cores by County\A Interim Shapefiles' + '\\' + arcpy.GetParameterAsText(1) + '.shp'  # Change this to the path of your output FC.

spatialref = arcpy.SpatialReference(4326) # Create the spatial reference object as WGS84. Can modify if desired.

#check for and erase temporary data
testData = r'N:\ReferenceMaterials\ArcGIS Python\Pavement Cores by County\A Interim Shapefiles'
if len(os.listdir(testData)) == 0:
    for t in listdir(testData):
        if t.endswith('.shp'):
            arcpy.Delete_management(os.path.join(testData, t))

arcpy.CreateFeatureclass_management(os.path.dirname(outfc), os.path.basename(outfc), "POINT", None, None, None, spatialref)

csv.register_dialect("xls", delimiter=",", lineterminator="\n") # Register the dialect for native CSV syntax in Microsoft Excel.
f = open(incsv, "r")
reader = csv.reader(f, dialect = "xls")

headers = reader.next() # Read the first line as the header names.

for header in headers[2:]: # Add fields for remaining columns if needed. Default is TEXT field.
    arcpy.AddField_management(outfc, header, "TEXT")

cursor = arcpy.da.InsertCursor(outfc, ['SHAPE@XY'] + headers[2:]) # Create InsertCursor.
count = 0
for row in reader:
    if count % 1000 == 0:
        print "processing row {0}".format(count)
    Ycoord = row[0] # Make sure 'Lat' is in the 1st column.
    Xcoord = row[1] # Make sure 'Lon' is in the 2nd column.
    newrow = [(float(Xcoord), float(Ycoord))] + row[2:]
    cursor.insertRow(newrow) # Insert point in FC for each row in CSV.
    count += 1

del cursor

#set variables for mxd and dataframe
mxd = arcpy.mapping.MapDocument('CURRENT')
df = arcpy.mapping.ListDataFrames(mxd, '*')[0]

#import new shapefile into dataframe
newLayer = arcpy.mapping.Layer(outfc)
arcpy.mapping.AddLayer(df, newLayer, 'TOP')

#select attribute (in this case, zip code)
InputFeatureClass = arcpy.GetParameterAsText(1)
InputField = 'zipCode'
InputValue = arcpy.GetParameterAsText(2)
whereclause = """{} = '{}'""".format(arcpy.AddFieldDelimiters(InputFeatureClass, InputField), InputValue)
arcpy.SelectLayerByAttribute_management(InputFeatureClass, "NEW_SELECTION", whereclause)
  • With this where you are getting all the results? Try running the tool in arcmap and copy as python script – NettaB Aug 27 '19 at 15:46
  • I've run it as a tool and in the python window, with the same result. – SarahKelley Aug 27 '19 at 15:50
  • what error are you getting with 1=1 arcpy.SelectLayerByAttribute_management(arcpy.GetParameterAsText(1), 'NEW_SELECTION', "'1=1'") – NettaB Aug 27 '19 at 15:57
  • 1
    I would recommend writing the script without using arcpy.GetParameterAsText(). Once you get the script working, convert it to a script tool. Also try ' "zipCode" = 97526 ' in the event that the zipCode field is an integer field rather than text. – Aaron Aug 27 '19 at 16:01
  • 1
    You'll need to surround the second brackets with single quotes since your zipcode field is text, not integer. – smiller Aug 27 '19 at 19:17

Try using arcpy.AddFieldDelimiters(fcname, fieldname) to add your formatting for the field.

You can also use string formatting such as

"""{} = '{}'""".format(arcpy.AddFieldDelimiters(fcname, fieldname), zipcode)

Note: You'll need to surround the second brackets with single quotes since your zipcode field is text, not integer.


Since the field names should be in double quotes and strings should be in single quotes - it is possible to create a valid expression with further concatenation: arcpy.SelectLayerByAttribute_management(arcpy.GetParameterAsText(1), "NEW_SELECTION", '"zipCode" in ' + "('97526')")

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.