Saturday 6 August 2016

arcpy - Looping on the Select_analysis tool


Im trying to perform a loop on the Select_Analysis tool in Arcgis. Code looks like this:



inputfile = open("locality.txt", 'r') # locality.txt is a txt file of locality names
loc_list = []
for line in input_file:
loc_list.append(line)
for i in loc_list:
arcpy.Select_analysis("locality.shp", "AOI.shp", " \"LOCALITY\" = '%s'" % (i))

where 'LOCALITY' is a field in 'locality.shp'.


The error returned is "AOI.shp" already exists. I conceptually understand why this isn't working, but is there a way I can make a selection in python for the list of localities in 'locality.txt' and create a new shapefile/FC based on that selection. I only want one shapefile with all the selected localities in this shapefile. There are about 600 localities, so creating 600 individual shapefiles and merging them into one at the end of the script is something I would like to avoid.


I feel like there is a simple solution to this and I am overlooking something easy.



I'm also aware of list concatenation, but only recently aware, so haven't yet used it in any of my code.



Answer



Each time you run through the second for loop, you're overwriting the previous AOI.shp file with the next selection.


How about adding a line above the selection command that changes the name of the output shapefile:


for i in loc_list:
AOI = "AOI_"+ i + ".shp"
arcpy.Select_analysis("locality.shp", AOI, " \"LOCALITY\" = '%s'" % (i))

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...