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():
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
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") 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 ???