I am trying to write a script to walk through all folders in my workspace and find and compact all geodatabases in my workspace. I feel like I'm on the right track but I am stuck.

import acrpy, os
from arcpy import env

arcpy.env.workspace "C:"

for (path, dirs, files) in os.walk(arcpy.env.workspace)
    for file in files
        if ".gdb" in file:
        workspaces = arcpy.ListWorkspaces("*", "FileGDB")
            for workspace in workspaces:

I am using ArcGIS 10.2.2 for Desktop.

  • Would you be able to edit your question to include the version of ArcGIS for Desktop that you are using, please? If it is 10.1 SP1 or later then arcpy.da.Walk becomes available. – PolyGeo Jan 7 '15 at 19:52
  • I am using 10.2.2 – kejad Jan 7 '15 at 19:53
  • question updated to include release version – kejad Jan 7 '15 at 19:57
  • 2
    Where are you stuck? If you are getting an error message then include that in your question. – PolyGeo Jan 7 '15 at 20:20

There are several errors in your code.

First, a file geodatabase is a directory, not a file, so you'll want to iterate over the directories, not the files. Second, arcpy.ListWorkspaces lists workspaces in the current directory, not the directory you are iterating over in your loop. Also, it is unnecessary as the arcpy.Compact_management will accept paths as string. (It does weed out any possible directories with ".gdb" in the that might not be geodatabases.) Finally, pay attention to your indenting, as this is very important to the python interpreter to separate blocks of code. Always indent after a colon (:) Try the following:

import arcpy, os
from arcpy import env

arcpy.env.workspace = r"C:/"

for path, dirs, files in os.walk(arcpy.env.workspace):
    for dir in dirs:
        if ".gdb" in dir:
            workspace = print os.path.join(path, dir)

To test, you could substitute print workspace for the call to arcpy.Compact_management, just to make sure you are hitting all the geodatabases you expect.

  • Thanks Arnold. I got a syntax answer but got it working by inserting workspaces = arcpy.ListWorkspaces("*", "FileGDB") on line 9. thanks for your help! – kejad Jan 7 '15 at 20:58
  • @kejad could you tell the changes you have made to the code. Exactly showing the same syntax error for me. – joseph_k Apr 27 '16 at 15:39
  • OK. As you have mentioned i've inserted workspaces = arcpy.ListWorkspaces("*", "FileGDB"). But that will list only the gdb's in the current directory. In the original code provided by Arnold, workspace = print os.path..print has to be removed. – joseph_k Apr 27 '16 at 15:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.