TransWikia.com

Clipping by looping through list using ArcPy

Geographic Information Systems Asked on April 13, 2021

I’m having trouble creating a looping function that looks through a geodatabase, clips each feature class to a "study_area" polygon, and puts the clipped files in a separate geodatabase. I keep getting "Could not clip feature classes". The features can all be clipped individually but trying to run this loop doesn’t work.

What am I missing here?

I tried to search for similar questions but only found answers regarding raster clips. Code below.

from arcpy import env


# setting my source and target geodatabase 
SourceWorkspace = r"E:UFD Commercial CorridorRoosevelt.gdb"
TargetWorkspace = r"E:UFD Commercial CorridorClipped.gdb"

#setting my clip feature (which is a polygon)
clipfeature = r"E:UFD Commercial CorridorClip area.gdbstudy_area"

env.workspace = SourceWorkspace

try:
    fclist = arcpy.ListFeatureClasses()

    for fc in fcList:
        outClipFeatureClass = targetWorkspace + "//Studyarea_" + fc

        arcpy.Clip_analysis(fc,clipfeature,outClipFeatureClass)

except: 
    arcpy.AddError("Could not clip feature classes")
    print ("could not clip feature classes")
    print arcpy.GetMessages() 

One Answer

I see two problems:

  1. you are defining TargetWorkspace though you are calling targetWorkspace. Python is case-sensitive.

  2. You need to properly join together strings to create paths. I highly recommend becoming familiar with os.path.join(). For example

Instead of:

outClipFeatureClass = targetWorkspace + "//Studyarea_" + fc

Use:

outClipFeatureClass = os.path.join(TargetWorkspace, "Studyarea_" + fc)

import arcpy
import os

# setting my source and target geodatabase 
SourceWorkspace = r"E:UFD Commercial CorridorRoosevelt.gdb"
TargetWorkspace = r"E:UFD Commercial CorridorClipped.gdb"

#setting my clip feature (which is a polygon)
clipfeature = r"E:UFD Commercial CorridorClip area.gdbstudy_area"

env.workspace = SourceWorkspace

fclist = arcpy.ListFeatureClasses()

for fc in fcList:
    outClipFeatureClass = os.path.join(TargetWorkspace, "Studyarea_" + fc)
    arcpy.Clip_analysis(fc,clipfeature,outClipFeatureClass)

Correct answer by Aaron on April 13, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP