TransWikia.com

Loop through input and erase features arcpy.Erase_analysis()

Geographic Information Systems Asked by Ecostrider on May 8, 2021

I am attempting to loop through two folders, one of input files (watershed polygons) and erase features (area boundaries) using arcpy.Erase_analysis

Here is my current code:

in_cover = "G:/Files/Watersheds"

erase_cover = "G:/Files/Areas"

out_cover = "G:/Output/Erase_output/"



arcpy.env.workspace = in_cover 
    for fc in [os.path.join(in_cover, x) for x in arcpy.ListFeatureClasses()]:
         print fc
          arcpy.env.workspace = erase_cover
          for fc2 in [os.path.join(erase_cover, y) for y in arcpy.ListFeatureClasses()]:
               print fc2
                 arcpy.Erase_analysis(in_features = fc, erase_features = fc2,
                                         out_feature_class = out_cover + "UNP_" + fc)

Running this, I get this error:

ExecuteError: Failed to execute. Parameters are not valid.
ERROR 000725: Output Feature Class:
Dataset G:OutputErase_outputXXX1.shp already exists.

It seems like the second loop is returning all files in the folder instead of one. For example, if i remove the erase function and just print, here’s what happens:

arcpy.env.workspace = in_cover 
        for fc in [os.path.join(in_cover, x) for x in arcpy.ListFeatureClasses()]:
            print fc
            arcpy.env.workspace = erase_cover
            for fc2 in [os.path.join(erase_cover, y) for y in arcpy.ListFeatureClasses()]:
                print fc2

This returns:

G:/Files/WatershedsWS1.shp
G:/Files/AreasArea1.shp
G:/Files/AreasArea2.shp
G:/Files/AreasArea3.shp
G:/Files/AreasArea4.shp
G:/Files/AreasArea5.shp
G:/Files/WatershedsWS2.shp
G:/Files/AreasArea1.shp
G:/Files/AreasArea2.shp
G:/Files/AreasArea3.shp
G:/Files/AreasArea4.shp
G:/Files/AreasArea5.shp
G:/Files/WatershedsWS3.shp
G:/Files/AreasArea1.shp
G:/Files/AreasArea2.shp
G:/Files/AreasArea3.shp
G:/Files/AreasArea4.shp
G:/Files/AreasArea5.shp

…And so on.

How can I fix this?

One Answer

ListFeatureClasses doesn't return the full path to the feature class. It only returns the name. Then, within the outer loop, you change workspaces. So, in your call of Erase, you're passing G:/Files/Areas/[fc] instead of then intended G:/Files/Watersheds/[fc].

To resolve this, where you iterate over the feature classes in "in_cover", use a list comprehension to create the full path:

for fc in [os.path.join(in_cover, x) for x in arcpy.ListFeatureClasses()]:

Answered by Tom on May 8, 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