I am trying to loop (for 630 layers) through the code to add a layer to the current mxd, change the title according to the layer name and export the map. My code is running fine for a single layer but I can't get it to loop using a list.
I attach the working single layer code:
import arcpy, os
mxd=arcpy.mapping.MapDocument("CURRENT")
lyrFile=arcpy.mapping.Layer(r"C:\Temp\LAYERS\Acer_campestre.lyr")
df=arcpy.mapping.ListDataFrames(mxd,"Layers")[0]
arcpy.mapping.AddLayer(df,lyrFile)
arcpy.RefreshTOC()
arcpy.RefreshActiveView()
print mxd.filePath
maplayers=arcpy.mapping.ListLayers(mxd,"*Layer",df)
print maplayers
for lyr in maplayers:
lyrname=lyr.name
lyrname2=lyrname.replace("_Layer","")
lyrname3=lyrname2.replace("_"," ")
print lyrname3
for elm in arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT"):
if elm.name == "Species":
elm.text = lyrname3
else:
print "Element not updated!"
print elm.name
arcpy.RefreshActiveView()
arcpy.mapping.ExportToTIFF(mxd,r"C:\Temp\TIFF\_"+str(lyrname3)+".tif",resolution=300)
del mxd
Now here is a stripped down version of what's not working. I have stripped it down to the part where its falling over. It seems to be at addLayer I get an error - Object:create object layer invalid data source.
import arcpy, os
from arcpy import env
env.workspace="C:/Temp/LAYERS"
mxd=arcpy.mapping.MapDocument("CURRENT")
slayer=arcpy.ListFiles("*.lyr")
lcount=len(slayer)
print lcount
for filelay in slayer:
arcpy.env.OverwriteOutput=True
print filelay
df=arcpy.mapping.ListDataFrames(mxd,"Layers")[0]
lyrFile=arcpy.mapping.Layer(filelay)
arcpy.mapping.AddLayer(df,lyrFile)
arcpy.RefreshTOC()
arcpy.RefreshActiveView()
mxd.SaveACopy(r"C:/Temp/Project.mxd")
del mxd,lyrFile
From looking online this doesn't help either: (I just get an mxd error)
import arcpy, os
mapDoc=arcpy.GetParameterAsText(0)
lyrFiles=arcpy.GetParameterAsText(1)
layers=lyrFiles.split(";")
mxd=arcpy.mapping.MapDocument("CURRENT")
mxd=arcpy.mapping.MapDocument(mapDoc)
df=arcpy.mapping.ListDataFrames(mxd)[0]
for lyrFile in layers:
lyr=arcpy.mapping.Layer(lyrFile)
arcpy.mapping.AddLayer(df,lyr)
mxd.save()
Can anyone help please? I would really appreciate any advice - relatively new to python