Saturday 16 April 2016

arcgis desktop - How to Compact geodatabases in multiple directories using ArcPy?


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:
arcpy.Compact_management(workspace)

I am using ArcGIS 10.2.2 for Desktop.



Answer



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)
arcpy.Compact_management(workspace)

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.



No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...