1

I tried this standalone script to turn off all layers in the MXD:

print "This script turns off the following layers:"
    try:
        arcpy 
    except NameError:
        import arcpy
    mxd = arcpy.mapping.MapDocument(r"PATH")
    for lyr in arcpy.mapping.ListLayers(mxd):
        print lyr.name
        lyr.visible = False
    mxd.save

It is adapted from the script mentioned for the Python window here:

https://geonet.esri.com/thread/16415

The standalone one I created for IDLE from this, above, did not affect the visibility status of any layers when I opened the MXD afterward to check. This is strange because running the same script within the Python window turned off all the layers for me.

Any clues?

  • 1
    Off topic, but I'm curious about the try/except import arcpy bit at the start of your code. I believe that if a module is already imported, python just ignores a second import of the same module. Thus, you can simply use import arcpy and get the same effect. Is there a reason I'm missing for why the try/except? – Emil Brundage Aug 16 '15 at 17:36
  • That's good to know. I found that bit of script in a post from someone who thought it would import arcpy every time. Now that I know it doesn't, and they're wrong :-), I will remove it. – ndthl Aug 17 '15 at 5:07
5

The reason why this code is failing is down to you missing () off the save method on your MXD, so you were not saving your changes. This code worked for me

import arcpy
print "This script turns off the following layers:"
mxd = arcpy.mapping.MapDocument(r"C:\Scratch\newcode.mxd")
for lyr in arcpy.mapping.ListLayers(mxd):
    print lyr.name
    lyr.visible = False

mxd.save()
del mxd

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.