Using ArcGIS 10.3, Python 2.7.8.
I have x
.shp and y
.lyr files. I am trying to loop through the shapefiles folder and the
lyr folder and to create x * y
.mxds that each contains one shapefile and one .lyr file.
import os import arcpy workspace = os.getcwd() lyrFolder = workspace + '\\Lyr\\' shpFolder = workspace + '\\Shp\\' mxd = arcpy.mapping.MapDocument(workspace + 'empty.mxd') dataFrame = arcpy.mapping.ListDataFrames(mxd,"*") for shapefile in os.listdir(shpFolder): if shapefile.endswith(".shp"): shpLayer = arcpy.mapping.Layer(shpFolder + shapefile) arcpy.mapping.AddLayer(dataFrame,shpLayer) shpName = shpLayer.name for lyrFile in os.listdir(lyrFolder): if lyrFile.endswith(".lyr"): lyrLayer = arcpy.mapping.Layer(lyrFolder + lyrFile) arcpy.mapping.AddLayer(dataFrame,lyrLayer) lyrName = lyrLayer.name mxdName = shpName + "_" + lyrName mxd.saveACopy(mxdDir + mxdName + '.mxd')
I expected to create the map documents, each one containing 1 shapefile and 1 layer file, as suggested with this minimal example:
shapefiles = [shp1, shp2] layerfiles = [lyr1, lyr2, lyr3, lyr4] mxd = [mxd1, mxd2, mxd3, mxd4, mxd5, mxd6, mxd7, mxd8] mxd1 = shp1 + lyr1 mxd2 = shp1 + lyr2 mxd3 = shp1 + lyr3 mxd4 = shp1 + lyr4 mxd5 = shp2 + lyr1 mxd6 = shp2 + lyr2 mxd7 = shp2 + lyr3 mxd8 = shp2 + lyr4
The problem is that each time a new document is created, the previous file is also added, as below:
mxd1 = shp1 + lyr1 mxd2 = shp1 + lyr1 + lyr2 mxd3 = shp1 + lyr1 + lyr2 + lyr3 mxd4 = shp1 + lyr1 + lyr2 + lyr3 + lyr4 mxd5 = shp1 + shp2 + lyr1 mxd6 = shp1 + shp2 + lyr1 + lyr2 mxd7 = shp1 + shp2 + lyr1 + lyr2 + lyr3 mxd8 = shp1 + shp2 + lyr1 + lyr2 + lyr3 + lyr4
I have tried adding
os.system("TASKKILL /F /IM ArcMap.exe") at the end of the second loop, but this only seems to solve the problem with the shapefiles: every new document is created with a single shapefile, but the
lyr files still pile up till the last