Select to view content in your preferred language

add shapefiles

1601
3
03-27-2012 01:55 AM
ReneSchulenberg
Emerging Contributor
Sometimes the most simple tasks are to most complicated (and thereby frustrating). I just want to add a shapefile in a mxd. I only am able to figure out how to add a layer file:

import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\gisbestanden\pythontest\test.mxd")
df = arcpy.mapping.ListDataFrames(mxd)[0]
addLayer = arcpy.mapping.Layer(r"C:\gisbestanden\pythontest\buurten.lyr")
arcpy.mapping.AddLayer(df, addLayer, "AUTO_ARRANGE")
mxd.saveACopy(r"C:\gisbestanden\pythontest\test7.mxd")
del mxd

I see two options, but excuting is another story. First replace addLayer = arcpy.mapping.Layer(r"C:\gisbestanden\pythontest\buurten.lyr") with addLayer = arcpy.mapping.Layer(r"C:\gisbestanden\pythontest\testje.shp") . But that doesn't work. Another one is the make a .lyr from C:\gisbestanden\pythontest\testje.shp, but I can't figure out how? Does anybody have a sollution
Tags (2)
0 Kudos
3 Replies
MathewCoyle
Honored Contributor
It depends if you want to make this layer permanent, as in create a .lyr file, or just add it to the map as a one off. You can accomplish the later using make feature layer.
0 Kudos
ReneSchulenberg
Emerging Contributor
I wanted the second. makefuturelayer worked in combination with addlayer:

arcpy.MakeFeatureLayer_management("C:\gisbestanden\pythontest\gedoe.shp", "test")
addLayer = arcpy.mapping.Layer("test")
arcpy.mapping.AddLayer(df, addLayer, "AUTO_ARRANGE")
0 Kudos
MathewCoyle
Honored Contributor
Seems like that isn't possible when working in a stand alone script. The following worked for me.

import arcpy, os
arcpy.env.worksace = workspace = r"C:\GIS\scratch"
arcpy.env.overwriteOutput = True
mxd_string = r"C:\GIS\MXDs\empty_test.mxd"
fc = r"C:\GIS\someshapefile.shp"
mxd = arcpy.mapping.MapDocument(mxd_string)
df = arcpy.mapping.ListDataFrames(mxd)[0]

outlayer = "TEST_LYR"
layerfile = os.path.join(workspace,"ADDED_LAYER.lyr")

arcpy.MakeFeatureLayer_management(fc, outlayer)
arcpy.SaveToLayerFile_management(outlayer, layerfile, "ABSOLUTE")
addlayer = arcpy.mapping.Layer(layerfile)
arcpy.mapping.AddLayer(df, addlayer)

mxd.save()
del mxd
print "done"
0 Kudos