3

I have a shapefile with table with area code (field areacode).

How can I export with ArcPy each unique area code so I get a SHP file for each one?

It takes too long to select the layer and query each area code and then export manually to SHP file.

1

You can use a SearchCursor to export features in a shapefile to new shapefiles. The SHAPE@ token allows you to access individual feature geometry. The Feature Class To Feature Class (Conversion) tool does the conversion to shapefile. You can also specify a subset of features you would like to export by specifying a query

query = """"areacode" > 2"""

import arcpy

shp = r'C:\path\to\your\shapefile'
outpath = r'C:\out\path'

query = """"areacode" > 2"""

with arcpy.da.SearchCursor(shp, ["SHAPE@", "areacode"], query) as cursor:
    for row in cursor:
        # Note* using the "areacode" to name the output
        arcpy.FeatureClassToFeatureClass_conversion (row[0], outpath, row[1])
| improve this answer | |
  • Thanks this works for me But when I search for areacode I it is ok but when I use it on postalcode I get error areacode is Long and postalcode is String raise e ExecuteError: ERROR 999999: Error executing function. An invalid SQL statement was used. An invalid SQL statement was used. Failed to execute – Sigster Sep 17 '14 at 10:12
  • @Sigster If you are querying a new field, you should add it to the field list. For example: ["SHAPE@", "areacode", "postalcode"]. You can then reference the new postalcode field by calling row[2]. – Aaron Sep 17 '14 at 13:24
  • No this is field I already have in the shp file with your sample it was in endless loop so I query like this with the postalcode it work well and no problem with but if I use this on areacode I get error area_code is Type String import arcpy fc = "C:\\Samples\\shipefile.shp" where = """"postalcode" = 1100""" arcpy.FeatureClassToFeatureClass_conversion(fc, "C:\\Samples\\ut", "1100_street.shp", where) the error if I query area_code what is TypeString raise e ExecuteError: ERROR 999999: Error executing function. An invalid SQL statement was used. An invalid SQL – Sigster Sep 17 '14 at 15:04
  • Fix this where = '"postalcode" = \'8000\'' Regards Sigster – Sigster Sep 19 '14 at 11:32

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