1

I try to add layer (abc) to several mxd files with arcpy and ignoring mxd file which called "land use" . I work with arcview 10.3 :

import arcpy,os,sys,string,datetime
import arcpy.mapping
from arcpy import env

env.workspace = r"C:\Project"
Layer1 = arcpy.mapping.Layer(r"C:\Project\layers\abc.lyr")
for mxd in arcpy.ListFiles("*.mxd"):
    if mxd == 'land use':
        continue
        print 'land use no encountered'
    print mxd
    mapdoc = arcpy.mapping.MapDocument(r"C:\Project\\" + mxd)
    df = arcpy.mapping.ListDataFrames(mapdoc, "Layers")[0]  
    arcpy.mapping.AddLayer(df ,Layer1, "TOP") # TOP \ BOTTOM \ AUTO_ARRANGE
    print 'AddLayer'
    mapdoc.save()
del mxd

as a result, arcpy add the layer to all mxd files and this is a bad result:

>>> 
land use 2.mxd
AddLayer
land use 3.mxd
AddLayer
land use.mxd
AddLayer
2

You need to filter away those map documents which contain "land use" in their names. It is better to test and if the evaluation gave us "false", proceed with the processing.

env.workspace = r"C:\Project"
Layer1 = arcpy.mapping.Layer("abc.lyr")
for mxd in arcpy.ListFiles("*.mxd"):
    if 'land use' not in mxd:
        print mxd
        mapdoc = arcpy.mapping.MapDocument(os.path.join(env.workspace,mxd))
        df = arcpy.mapping.ListDataFrames(mapdoc, "Layers")[0]
        arcpy.mapping.AddLayer(df ,Layer1, "TOP") # TOP \ BOTTOM \ AUTO_ARRANGE
        print 'AddLayer'
        mapdoc.save()
        del mxd

Another thing to consider is that it is usually better to use the os.path.join when specifying the data path instead of concatenating strings. Also keep in mind that only those .mxd files will be ignored that don't contain 'land use' in their names. Files that are named "LandUse", "Land Use" will be processed because we are evaluating only "land use". You could add more if statements to evaluate those cases.

  • 1
    If you don't need case sensitivity and specifically want to exclude 'land use', then instead of Alex's "if 'land use' not in mxd", you could use: if os.path.splitext(mxd.lower())[0] != 'land use' – T. Wayne Whitley Apr 20 '15 at 11:44

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.