[GIS] Looping through multiple feature datasets and Intersect Files

arcpy

I am getting an error with a python script I have created. I have 1 geodatabase with 3 feature datasets. What I would like to do, is loop through 1 feature dataset (NB) to get a list of feature classes. One by one, I would like to get the name of the feature class (ID_NB) and search for its corresponding feature class in another dataset (called CCH) so that I can perform the Intersect function on the two files and save the output in the 3rd feature dataset and call it ID_Ints. **There may not always be a matching feature dataset between the two either.

The script works fine the first time through, but when it comes to the second feature class, it gives me an error saying "Dataset does not exist or is not supported". I have a feeling it is because I have switched workspaces in a for loop, but I can't think of another way around this.

Anyone have any ideas?

#Define Environments
CCHws = "C://TEST.gdb//CCH"
PerMap = "C://TEST.gdb//NB"
opws = "C://TEST.gdb//opws"

#Set workspace
arcpy.env.workspace = PerMap
arcpy.env.overwriteOutput = True
NBList = arcpy.ListFeatureClasses()

#Start forloop, find first NB Feature Class and extract the ID (the first 5 characters)
for NB in NBList:
    NBname = NB[:5]
    NBname2 = NBname + "*"
    NBnameEx2 = "\"" + NBname2 + "\""

#Calculate Original Area of NB feature Class
    arcpy.AddField_management(NB, "NB_Area", "DOUBLE")
    arcpy.CalculateField_management(NB,"NB_Area","!shape.area@meters!","PYTHON")

#Set variables to use in Intersect
    CCH = str(CCHws) + "//" + str(NBname) + "_CCH" 
    opresult = opws + "//" + str(NBname) + "_Ints"
    NBfile = str(PerMap) + "//" + str(NBname) + "_NB"

#Re-set workspace to look for matching ID with an '_CCH' in the CCH dataset
    arcpy.env.workspace = CCHws
    arcpy.env.overwriteOutput = True
    cchList = arcpy.ListFeatureClasses(NBname2)
    for cch in cchList:
        if len(cchList) > 0:
            arcpy.Intersect_analysis([NBfile,CCH],opresult)  
        else:
            print NBname + " Does not have a matching CCH"

Best Answer

You are correct. You need to reset your workspace again at the end of your nested for loop (CCH in cchList). Try this:

#Re-set workspace to look for matching ID with an '_CCH' in the CCH dataset
    arcpy.env.workspace = CCHws
    cchList = arcpy.ListFeatureClasses(NBname2)
    for cch in cchList:
        if len(cchList) > 0:
           arcpy.Intersect_analysis([NBfile,CCH],opresult)  
        else:
            print NBname + " Does not have a matching CCH"
    arcpy.env.workspace = PerMap

You also only need to specify the arcpy.env.overwriteOutput = True once at the top of the script like you have so I removed the second reference to it in your nested for loop. Hope this helps.

Related Question