I am trying to automate various tasks in ArcGIS Desktop (using ArcMap generally) with Python, and I keep needing a way to add a shapefile to the current map. (And then do stuff to it, but that's another story).
The best I can do so far is to add a layer file to the current map, using the following ("addLayer" is a layer file object):
def AddLayerFromLayerFile(addLayer):
import arcpy
mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
arcpy.mapping.AddLayer(df, addLayer, "AUTO_ARRANGE")
arcpy.RefreshActiveView()
arcpy.RefreshTOC()
del mxd, df, addLayer
However, my raw data is always going be shapefiles, so I need to be able to open them. (Equivantly: convert a shapefile to a layer file without opening it, but I'd prefer not to do that).
3 Answers 3
Assuming there is no addshapefile
function, one solution would be:
Make Feature Layer (Data Management) - Syntax:
MakeFeatureLayer_management (in_features, out_layer, {where_clause}, {workspace}, {field_info})
Then add the layer...
I don't have ArcPy to hand but can you not use the MakeFeatureLayer tool and then add the result to your map?
arcpy.MakeFeatureLayer(r"C:\myData.shp","myData")
arcpy.mapping.AddLayer(df, "myData", "AUTO_ARRANGE")
This library reads and writes ESRI Shapefiles in pure Python. You can read and write shp, shx, and dbf files with all types of geometry. Everything in the public ESRI shapefile specification is implemented.
-
1I'm curious as to what's wrong with this solution? Thought it was an exact match for the question asked.Jacques Tardie– Jacques Tardie2011年05月09日 14:15:58 +00:00Commented May 9, 2011 at 14:15
-
This can be used to read/write shapefiles but the question is how to create a layer in ArcMap from a shapefile.2014年12月20日 07:51:40 +00:00Commented Dec 20, 2014 at 7:51