Adding a shapefile to a blank .mxd in Arcpy

4294
5
02-29-2016 01:37 PM
johnrogers4
New Contributor

How can you add several shapefiles to a blank .mxd using a script written with Arcpy? I've started with the code below. The code runs with no errors but the shapefile is not added to the blank .mxd. I'm not sure if you have to first convert the shapefiles to .lyr files? I am trying to run the script outside of ArcMap in command line window.

import arcpy
from arcpy import env

# get the map document
mxd
= arcpy.mapping.MapDocument("CURRENT")

# get the data frame
df
= arcpy.mapping.ListDataFrames(mxd,"*")[0]

# create a new layer
newlayer
= arcpy.mapping.Layer(path_to_shapefile_or_feature_class)

# add the layer to the map at the bottom of the TOC in data frame 0
arcpy
.mapping.AddLayer(df, newlayer,"BOTTOM")

0 Kudos
5 Replies
JakeSkinner
Esri Esteemed Contributor

Hi John,

If you are running this code within ArcMap in the Python window, try adding the line:

arcpy.RefreshActiveView()

0 Kudos
AravindStoryMaps
Esri Regular Contributor

Are you using (r'Path') or just ('Path) for "path_to_shapefile_or_feature_class"?

0 Kudos
DarrenWiens2
MVP Honored Contributor

Your code runs fine for me, referencing a shapefile. It adds the layer to the TOC.

newlayer = arcpy.mapping.Layer(r'C:\junk\points.shp')

Just make sure you're writing a proper Python path (like above).

0 Kudos
johnrogers4
New Contributor

I am trying to run the script outside of ArcMap in command line window.

0 Kudos
DarrenWiens2
MVP Honored Contributor

In that case, I'm surprised that it knows what "CURRENT" is (not saying it can't be done, I've just never done it that way). Do you have better luck running MakeFeatureLayer​?