Use list element to build new path

There are dedicated list functions in arcpy and I would use them rather than the python os.listdir function:

import arcpy, os

workspace = r"C:\test"
arcpy.env.workspace = workspace
arcpy.env.scratchworkspace = workspace
arcpy.env.overwriteOutput = True

firstlevelList = arcpy.ListWorkspaces(workspace_type = "Folder")

for element in firstlevelList:
    arcpy.env.workspace = element
    secondlevelList = arcpy.ListFiles()
    for file in secondlevelList:
        # do something

file represents the file itself even though if you print it you will only get its name. You can input it to a tool without having to recreate the full path to the file. Nevertheless if you want to do this for some reason, add this line under the last for block:

path_to_file = os.path.join(ws, file)

Depending on the type of the files (rasters?) and what you want to do with them, another list function might be more approriate:

  • arcpy.ListRasters()
  • arcpy.ListDatasets()
  • arcpy.ListFeatureClasses()
  • ...

See also the help page for arcpy.ListWorkspaces() and arcpy.ListFiles().

Tags:

List

Arcpy