1

This question already has an answer here:

UPDATE: I am able to save the progress, and make the added layer actually show up in the TOC, by using mxd.saveACopy rather than mxd.save():

mxd.saveACopy(r"W:\for\RSI\DKL\General_User_Data\gamos\Projects\01_Tenures_Mobile_Map\Highway_intersections_2.mxd")

The downside is this way requires me to create a new .mxd, rather than save to an existing .mxd


I am trying to add a layer file to the TOC in using the arcpy.mapping.AddLayer method in Python, but it won't show up:

arcpy.mapping.AddLayer(df, lyr, "TOP")
arcpy.RefreshActiveView(),arcpy.RefreshTOC() 
layers = arcpy.mapping.ListLayers(mxd) #Returns the object list of layers
print"Here are the layers in the TOC:"
print"========================================"
for layer in layers:
    print layer.name

df and lyr are objects, "TOP" is the position it should be inserted.

After I do addLayer, I grab the ListLayers object from the mxd, then print out all the individual layers. It's there - so why can't I see it in the TOC in ArcMap ??

Here is how I grab my mxd and df objects, add the Layer, and (attempt) to save the .mxd:

mxd = arcpy.mapping.MapDocument(r"W:\for\RSI\DKL\General_User_Data\gamos\Projects\01_Tenures_Mobile_Map\Finding_FSR_highway_intersections.mxd")
print (str(mxd) + " extracted OK")

#df = mxd.activeDataFrame
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
print (str(df) + " extracted OK")

arcpy.mapping.AddLayer(df, lyr, "TOP") 

arcpy.RefreshActiveView()
arcpy.RefreshTOC()
mxd.save() #this will run inside the script OK, will run from an external script only if the mxd is closed ???

marked as duplicate by Midavalo Jul 5 '17 at 2:29

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    You are missing a quote mark in your first line - TOP" – Midavalo Jun 30 '17 at 22:54
  • 1
    Have you saved the MXD? – Midavalo Jun 30 '17 at 22:58
  • No - I get: IOError: MapDocObject: Unable to save. This may be part of the problem for sure.. – grego Jun 30 '17 at 23:14
  • 2
    Can you add the line of your mxd assignment to the code please? – fatih_dur Jul 1 '17 at 1:19
  • @grego In addition to the mxd assignment line as requested above, please also include the line where you save the mxd – Midavalo Jul 2 '17 at 15:22