-1

I am working with NLCD data set and am trying to extract changed pixels based on county boundaries (extract by mask). I have wrote a little script that will do the job BUT i was wondering if somehow I could use the boundary names as my output names because at the moment, the output is just 1, 2, 3, ... As you will see, I am using a counter. I tried counter = ctyList but it doesn't work. Here is the script:

import os
import arcpy
from arcpy import env
from arcpy.sa import *
env.workspace = "C:\Users\sr\Desktop\Sam\AllCounties"
ctyList = arcpy.ListFeatureClasses ("*.shp")
inRaster = "nlcdrecmosaic"
counter = 1
for shp in ctyList:
 out= arcpy.sa.ExtractByMask(inRaster,shp)
 out.save("C:\Users\sr\Desktop\Sam\AllCounties\out\mskd"+ str(counter))
 counter = counter + 1     

Thank you very much for your help. Sam

mvandiepen
  • 67
  • 12
SamR
  • 45
  • 5

1 Answers1

0
for shp in ctyList:
    county_name = shp.split('.')[0]  # Split the file name at the '.' to get just the name without the extension 
    out= arcpy.sa.ExtractByMask(inRaster,shp)
    out.save("C:\Users\sr\Desktop\Sam\AllCounties\out\mskd"+ county_name
BigGerman
  • 525
  • 3
  • 11
  • I am sorry if this question is a bit stupid, but for 'file_name_list' Do I just do as you have done or have to input the names of the counties? I don't quite understand the "name1, name2" I am very new to python so excuse my question. – SamR Dec 10 '18 at 20:32
  • You should actually just be able to use the feature class names in `ctyList`. I'll update my answer – BigGerman Dec 10 '18 at 20:38
  • thank you so much for your help. It seems to work. Just a question, I was wondering what is that [0] at the end of the split? Is it saying that do not keep anything after '.'? – SamR Dec 10 '18 at 22:29
  • Basically, yes. The `split` function splits a string at a specified character and then puts the resulting sub-strings into a list. So for the string 'countyname.shp' the above split would result in the list `['countyname', 'shp']`. The [0] is taking the element of the list at index 0, in this case, the string 'countyname'. – BigGerman Dec 11 '18 at 14:07