Search code examples
pythongisarcpy

arcpy.ListFeatureClasses() for multiple workspaces


I'm trying to use arcpy.ListFeatureClasses() for multiple workspaces within the same script. Looking through other example scripts, I thought I could simply assign workspaces to a variable, and then use that variable within arcpy.ListFeatureClasses()

for example:

workspace = "C:\\location\\"
fcs = arcpy.ListFeatureClasses(workspace)
for fc in fcs:
    print fc

but this results in an error:

 TypeError: 'NoneType' object is not iterable

I've gotten arcpy.ListFeatureClasses() to work when I'm only interested in the feature classes within the default workspace, like:

arcpy.env.workspace = "C:\\location\\"
fcs = arcpy.ListFeatureClasses()

But I'm interested in looking through different folders for each step of my script, and I don't want reset my default workspace for each step.

Furthermore, why have I seen the first example used in other people's scripts (including those of my GIS programming professor) and they seemed to work in those instances, but I get an error.

Thank you for any help or advice that can be provided.


Solution

  • Your first example will certainly not work. arcpy.ListFeatureClasses() takes 3 optional arguments and the workspace isn't part of them, it must be defined beforehand, see the Help page of the function for the exact syntax.

    Resetting the current workspace isn't such a big deal. Depending on the types of workspaces you work with (folder, geodatabase, SDE, various...) and how they are structured (are they all within the same location? Do you have a list of specific folders/databases?) you will first list them, then iterate over the workspaces to list their feature classes:

    # 1. List workspaces
    
    listWS = [r"C:\DATA", r"D:\PROJECT\geodatabase.gdb", r"D:\whatever.mdb"]
    # use this if the workspaces are in various locations
    
    # or: 
    
    arcpy.env.workspace = r"C:\DATA"
    listWS = arcpy.ListWorkspaces()
    # use this if the workspaces are in the same location
    
    # 2. Iterate over the workspaces and list their feature classes
    
    for ws is listWS:
     arcpy.env.workspace = ws
     listFC = arcpy.ListFeatureClasses()
     for fc in listFC:
      # do something
    

    See the Help page for arcpy.ListWorkspaces() to see how to restrict your list to certain types of workspaces or using a wildcard.