I've tried to develop some workflows with the ArcPy module for splitting a shapefile based on the unique values in a specified field. The code works as expected except one thing I am not able to figure out.
import arcpy, os
from arcpy import env
#getting user inputs
in_fc = arcpy.GetParameterAsText(0) #'roads.shp'
outfolder = arcpy.GetParameterAsText(1) #r'C:\GIS\Temp\OutSHP'
fieldname = arcpy.GetParameterAsText(2) #"FEATURE"
createfolder = arcpy.GetParameterAsText(3) #true/false
env.workspace = outfolder
#user chosen NOT to create a folder with the name of feature class
#
if createfolder == "false":
with arcpy.da.SearchCursor(in_fc, ["{0}".format(fieldname)]) as cursor: #defining a search cursor
for row in cursor:
if not arcpy.Exists(os.path.join(outfolder,row[0])): #checking if shapefile already exists
#Analysis toolbox > Extract > Select GP tool to select features
arcpy.Select_analysis(in_fc, os.path.join(outfolder,row[0]), ''' "FEATURE" = '{0}' '''.format(row[0]))
else:
print "The shapefile with this name already exists"
#user chosen to create a folder with the name of feature class
#
else:
with arcpy.da.SearchCursor(in_fc, ["{0}".format(fieldname)]) as cursor: #defining a search cursor
for row in cursor:
directory = os.path.join(outfolder,row[0]) #create a path for directory that will be created
if not os.path.exists(directory): #checking if directory exists
os.makedirs(directory)
if not arcpy.Exists(os.path.join(directory,row[0])): #checking if shapefile already exists
#Analysis toolbox > Extract > Select GP tool to select features
arcpy.Select_analysis(in_fc, os.path.join(directory, row[0]), ''' "FEATURE" = '{0}' '''.format(row[0]))
else:
print "The shapefile with this name already exists"
I've created a script tool in ArcGIS which takes an input shapefile, an output folder, a field name and whether user wants to create a folder for each unique value in the specified field before creating a shapefile there (the folder and the shapefile will have identical name except .shp in the end for shapefiles).
The issue is that the tool gets the work done for 5 seconds when user chooses to create folder with the unique name for each feature class and for around 3 minutes if the shapefiles are created directly in the output folder. I am having hard times trying to find out anything that could stipulate this behaviour in the code.
