Select to view content in your preferred language

Add a definition query to a layer in multiple mxd's

1365
3
04-16-2012 03:44 AM
ClaireParsons
Emerging Contributor
i hope someone can help - I have an number of mxd's in a folder each with the same layers in but a different spatial extent.
I'd like to write a script that applies the definition query to the layer in each of these MXD's - can someone help?
Tags (2)
0 Kudos
3 Replies
AndrewChapkowski
Esri Regular Contributor
You can use the mapping module to write a query definition to the layer.

Example:
from arcpy import mapping
import arcpy

mxd = mapping.MapDocument("CURRENT")
layers = mapping.ListLayers(mxd)
for layer in layers:
   layer.definitionQuery = "<FIELD> = '" + sql + "'"
   del layer
mxd.save()
del layers
del mxd


Hope this helps.
0 Kudos
MarcinGasior
Frequent Contributor
To change Definition Query in multiple MXD's try the following code:
import arcpy, os
workspace = r"C:\tmp\MapProjects"
try:
    for filename in os.listdir(workspace):
        fullPath = os.path.join(workspace,filename)
        if os.path.isfile(fullPath):
            basename, extension = os.path.splitext(fullPath)
            if extension.lower() == '.mxd':
                mxd = arcpy.mapping.MapDocument(fullPath)

                #here build your definition query as STRING eg.:
                defQuery = '"OBJECTID" < 100'
                #Replace YourLayerName with the layer name (String) which will be changed
                for myLayer in arcpy.mapping.ListLayers(mxd, 'YourLayerName'):
                    myLayer.definitionQuery = defQuery
                mxd.save()
except:
    arcpy.GetMessages()
del mxd, myLayer
0 Kudos
ClaireParsons1
Emerging Contributor
Hi guys

Thanks for your replies and help.  This is the code I have used.

import arcpy, glob, os

path = r"C:\Users\Documents\GIS\Drawings\Revisions 06042012"

mxdList = glob.glob(path + "\*.mxd")

for mxd in mxdList:
    mxd = arcpy.mapping.MapDocument(mxd)
    print mxd
    layers = arcpy.mapping.ListLayers(mxd,"Local Wildlife Sites")
    print layers
    for layer in layers:
        defquery = '"LWS_STATUS"' + " = 'pLWS'"
        print defquery
        layer.definitionQuery = defquery
        mxd.save()
0 Kudos