[GIS] Select polygons one by one and export them using arcpy

arcpyselect-by-attribute

I have a shapefile that contains 200+ metropolitan cities. In each city, there are some tract polygons. The dbf table looks like:

tract  city    xvar
1      0040    20
2      0040    12
3      0040    45
...    ...     ...
5      5602    22
6      5602    44
...    ...     ...

My goal is to select a city and save it as a separate shapefile the name of which is the same as the city code:

0040.shp

tract  city    xvar
1      0040    20
2      0040    12
3      0040    45
...    ...     ...

5602.shp

tract  city    xvar
5      5602    22
6      5602    44
...    ...     ...

How should I automate this process for all the cities using arcpy?

Best Answer

You can use Select (Analysis) to perform this operation. This method has the added benefit of preserving your attributes. There are two main steps:

  1. Use a generator to list all of the unique city codes
  2. Loop through unique cities codes and add the code to the Select SQL expression

import arcpy, os

# Define the output workspace
outws = r'C:\temp\out'

# Set the input shapefile
shp = r'C:\temp\test.shp'

# Get a list of unique city codes using a generator
cities = set(row[0] for row in arcpy.da.SearchCursor(shp, "city"))

# Select unique cities and export to new shapefiles
for c in cities:
    out_fc = os.path.join(outws, c) # Define the output name
    where_clause = '"city" = \'%s\'' % c # Select based on city name
    arcpy.Select_analysis(shp, out_fc, where_clause) # Perform the Select
Related Question