Python erroneously removing layers when renaming.

Discussion created by Jake_Diebolt on Dec 12, 2011
Latest reply on Dec 13, 2011 by jbarrette-esristaff
I'm having a problem when using Python for map automation. I've created a script that loops through the layers in my dataframe and replaces any underscores with a space (makes my layers more readable for my arcreader users, and saves me having to go through dozens of layers to remove the underscores).

When I write the code in the Python window, it works as expected, replacing the underscores with spaces. However, when I try to make it a tool in a toolbox, it messes up. All the layers containing underscores are removed from the map. Refreshing the TOC or View doesn't help; I've tried doing so with code or via buttons in arcmap. Saving within the script doesn't help either. I just can't figure out why it wouldn't work in a toolbox?

I've pasted my code below. Any help is appreciated:

ap = arcpy.mapping
mxd = ap.MapDocument("CURRENT")
df = ap.ListDataFrames(mxd)[0]
for lyr in ap.ListLayers(mxd,"",df):
    name = lyr.name
    newname = name.replace('_',' ')
    lyr.name = newname

EDIT: I have now tried running them as tools with 'Always run in foreground' unchecked so that the use of "CURRENT" doesn't mess things up. However now I receive a Runtime Error: Object: CreateObject cannot open map document. The layers are no longer removed as they were before, just get the error when running the tool. What does this mean?