[GIS] Save a selected row into a new shapefile with arcpy

arcmaparcpycursorexportshapefile

I have a shapefile with 100+ rows. What I like to do is to select each row and export all its data to a new shapefile. I tried using the arcpy.da.SearchCursor as follows:

with arcpy.da.SearchCursor(inputshape,"*",None) as cursor:
...     for row in cursor:
...         arcpy.FeatureClassToFeatureClass_conversion(row,pathToFolder,row[3] + ".shp")

Resulting in an error, arcpy displays following message:

Runtime error
Traceback (most recent call last):
File "", line 3, in
File "c:\program files (x86)\arcgis\desktop10.4\arcpy\arcpy\conversion.py", line 1694, in
FeatureClassToFeatureClass
raise e
RuntimeError: Object: Error in executing tool

I think first parameter in the FeatureClassTofeatureClass_conversion method ist wrong. Other Examples show that there has to be the @Shape field. the workflow I would like to automate is very simple: 1) Open the attribute table 2) select a row 3) Export selected data to a new shapefile.

Best Answer

The cursor does not select anything, it is only returning a tuple (~a list of the attributes). But you can use the ObjectID returned by the cursor and pass this to Select:

Extracts features from an input feature class or input feature layer, typically using a select or Structured Query Language (SQL) expression and stores them in an output feature class.

Like this:

import arcpy,os

input_fc=r'C:\TEST\Shape.shp'
outfolder=r'C:\folder'

with arcpy.da.SearchCursor(input_fc,'OID@') as cursor:
    for row in cursor:
        sql="""{0} = {1}""".format(arcpy.AddFieldDelimiters(input_fc, arcpy.Describe(
            input_fc).OIDFieldName),row[0])
        arcpy.Select_analysis(in_features=input_fc, out_feature_class=os.path.join(outfolder,'Shapefile_{0}.shp'.format(row[0])), 
                             where_clause=sql)

enter image description here

But an easier option would be to use tool Split By Attributes with ObjectID field as split field:

Splits an input dataset by unique attributes.

Related Question