2

we use definition queries to filter data to field users. We have up to 40-50 MXDs that are identical except for 1 variable in the definition query that allows the data for that MXD to be unique. Example - "DeploymentNumber='AA'" where 'AA' is the variable. So, when we update MXDs, we would like to be able to use a python script to be able to update the variable - 'AA' component of our definition query in each layer without having to open each MXD, click on each layer and manually update (which in some cases is a 5 minute operation per MXD).

3

You'll have to change this for your specific data since there might be layers that you don't want to change / don't have def queries set:

import os
import arcpy

# top level directory where all the map docs are
path = r"<path>" 

# recursively search the directory for .mxd files
def getMXD(path):
    for dirpath, dirnames, filenames in os.walk(path):
        for f in filenames:
            if f.endswith(".mxd"):
                yield os.path.join(dirpath, f)


for mapdoc in getMXD(path):
    # might need to change wildcarding here
    mxd = arcpy.mapping.MapDocument(mapdoc) 
    df = arcpy.mapping.ListDataFrames(mxd, "*")[0]

    for lyr in arcpy.mapping.ListLayers(mxd, "*", df):        
        if lyr.supports("DEFINITIONQUERY"):
            lyr.definitionQuery = "DeploymentNumber = 'AA'"
            mxd.save() # or mxd.saveACopy(<newpath>)

    del mxd, df
  • 2
    Was on my way to paste almost identical code :) suggest using mxd_files = arcpy.ListFiles("*.mxd") and then mxd_file_path = os.path.join(mxd_files_folder,mxd_file), a bit less code? – Alex Tereshenkov Nov 18 '15 at 6:39
  • @AlexTereshenkov, good point (and a lot simpler!) if all your map docs are in the same folder. You'll want os.walk() to recursively drill down into sub-folders as arcpy.ListFiles() only works on whatever is set to env.workspace. – Paul Nov 18 '15 at 6:50
  • ah you are right. You would need to change env.workspace every time you are in another directory.. was always wondering why a parameter input_folder was not implemented for the List* functions in arcpy, is there any specific reason for that? Would love to have arcpy.ListFeatureClasses(input_folder) :) – Alex Tereshenkov Nov 18 '15 at 6:57
  • 1
    @AlexTereshenkov, likely because the various List* functions are essentially file globbers with special consideration for ArcGIS data types (e.g., a file geodatabase is a folder). See the glob module for something similar. – Paul Nov 18 '15 at 7:04
  • I will get into that tomorrow when I get back into the office and let you know how I go. Much appreciated. – Kim G Nov 18 '15 at 7:20

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.