[GIS] Scripting a Loop of Clip (Analysis)

arcgis-desktopcliploop

I wish to loop function that clips a shapefile by a feature class. I want to make the clip the same as the input name. The names of the files are WVHGT_201403281200_f180_201404050000.shp and I just want f180 part as the output feature class. The clip feature will remain consistent throughout.

I have the syntax down from here. I am just not sure how the write the for loop to do this.

Best Answer

You can use Python's built-in .split() to extract that part of the name:

file = "WVHGT_201403281200_f180_201404050000.shp"
name = file.split("_")
print name[2]

>>>
f180

Now, integrate this into the for loop. I am assuming you are iterating through a collection of files rather than individual features.

import arcpy, os
from arcpy import env

env.workspace = r"C:\temp1"
outws = r"C:\temp2"

clip_features = r"C:\temp\clipper.shp"

fcs = arcpy.ListFeatureClasses()

for fc in fcs:
    name = fc.split("_")[2] # Extract part of the name
    out_feature_class = os.path.join(outws, name)  # Combine out workspace and filename 
    # Execute Clip
    arcpy.Clip_analysis(fc, clip_features, out_feature_class)
Related Question