I have spent hours attempting to find the solution to the following problem online, but all answers I have found are quite old, and none work. Here is the situation: I have a variety of .shp files. I have a blank mxd file. I want to add the .shp files into the .mxd file.

Various stackoverflow and stackexchange answers would have me believe that the answer to my problem lies in either: arcpy.MakeFeatureLayer_management(,) or arcpy.mapping.Layer()

Unfortunately, I get a similar error no matter what approach I take.

The exact code from my most recent attempt (I'm really not sure how this could possibly be simpler):

import arcpy
arcpy.env.workspace = "C:/test"
arcpy.Exists("shapefile.shp") #returns True

It is at this point that I receive the following error: Traceback (most recent call last): ... File "C:\Program Files\ArcGIS\Server\arcpy\arcpy\arcobjects\mixins.py", line 289 in init super(LayerMixin, self).init(lyrfile) File "C:\Program Files\ArcGIS\Server\arcpy\arcpy\arcobjects_base.py", line 47, in init for arg in args ValueError: Object: CreateObject Layer invalid data source

Edit: exact code from my attempt using the other function

import arcpy
arcpy.env.workspace = "C:/test"
arcpy.Exists("shapefile.shp") #returns True

In this case, I receive the following error: Traceback (most recent call last): ... arcgisscripting.ExecuteError: ERROR 000229: Cannot open shapefile.shp Failed to execute .

Can anyone advise me as to how to proceed? I have found almost five different solutions suggesting that this is the procedure which I should follow, but it definitely isn't working for me. I am using Python 2.7.

Additional Notes: -I have manually loaded the shapefile in ArcMap, it loads and displays correctly.

  • What does arcpy.Exists(yourFile) return? Your path has forward slashes. Try "Z:\\program\\..\\shapefile.shp". – gm70560 Jan 23 '15 at 23:08
  • I have tried. Trust me, I have tried every combination of escapes, slashes, and string literals for the filepath. I get the same error no matter which. I used the os module to confirm the file's existence, but haven't tried arcpy.Exists. I'll do that now. – gisuser Jan 23 '15 at 23:25
  • MakeFeatureLayer has 2 required parameters. You need an output layer, like: arcpy.MakeFeatureLayer_management("C:/blah/blah.shp", "myNewLayer") – phloem Jan 23 '15 at 23:25
  • Apologies, error in the question. I am passing two parameters, I'll update that now. – gisuser Jan 23 '15 at 23:26
  • arcpy.Exists(myfile) returns True – gisuser Jan 23 '15 at 23:29

You're improperly using the arcpy.mapping.Layer function.

arcpy.mapping.Layer takes a Layer File (*.lyr) saved on disk and returns a Layer Object from that.

Layer Objects have methods which you can use to change various properties of the layer, such as its visibility, transparency, definition query, etc.

You're giving it a shapefile. Hence the error, invalid data source.

Just use the MakeFeatureLayer_management function which will create an in_memory Feature Layer and automatically add it to the current MXD, where the first argument is the absolute path to your shapefile, and the second argument is a string representing the name of the layer as it will appear in the Table of Contents.

arcpy.MakeFeatureLayer_management(r"C:\SomeDataPath\shapefile.shp", "MyShapefile")
| improve this answer | |
  • Thanks so much for the response! :) Unfortunately, this still doesn't work. Please see my edit on the original question, I get an error "Cannot open shapefile.shp" – gisuser Jan 25 '15 at 0:04
  • gisuser, error 000229 is an error that comes from an input not being accessible. Typical causes of this are that the dataset is corrupt or that the way it was provided is invalid, such as a typo in the path or name. Instead of relying on the environment workspace to find the shapefile, just try providing it as an absolute path to the shapefile as the first argument. Do you still get error 229 when doing that? If so, can you provide a screen shot? Also, are you doing this in the Python window, a script tool, a custom toolbox or Python Toolbox? – MrBubbles Jan 25 '15 at 0:12
  • I do get the same error when I specify an absolute filepath. I have tried in the Python Toolbox and in the Python window, I haven't yet tried executed an actual independent script because I wanted the additional error checking provided by the immediate windows. Suggestions? – gisuser Jan 25 '15 at 18:42
  • I would suspect there might be something funky about your shapefile at this point. Try recreating it. – MrBubbles Jan 25 '15 at 22:26

I have finally solved the problem - it was actually a simple fix - a misunderstanding on my part. I failed to realize that a "shapefile" is far more than just the ".shp" file. Apparently you need to have all (five?) files (with all (five?) extensions) in the appropriate directory in order for the function to work properly. After adding my .dbfs, my .xmls, etc., it works just fine.

| improve this answer | |

The following code contains more than you need, but it will show that you need to specify or create a blank mxd, then specify a data frame, then activate that data frame then add your layers/shapefiles with optional symbology specified


Author:   Dan.Patterson@carleton.ca
Purpose:  create a base mxd and populate it with default values
Requires: specify the files to load and the default dataframes etc
template paths
C:\Program Files (x86)\ArcGIS\Desktop10.2\MapTemplates\Traditional Layouts\LetterLandscape.mxd
C:\Program Files (x86)\ArcGIS\Desktop10.2\MapTemplates\Traditional Layouts\LetterPortrait.mxd
import arcpy
import sys
import os
import shutil

script = sys.argv[0]  # script name and location
mxd_src = "C:/!test/mapping/mxd_test02.mxd"  # a shell empty project
path, doc = os.path.split(mxd_src)
template = path + "/LetterPortrait.mxd"

arcpy.env.workspace = path + "/shapefiles"
arcpy.overwriteOutputs = True

shp_files = ["AOI_mtm9.shp", "RandomPnts.shp"]
lyr_files = ["AOI_mtm9.lyr","RandomPnts.lyr"]
arcpy.ListFiles("*.lyr")    #use this to check above

author = "This could be you!!!!"
description = "Demo project working with the arcpy.mapping module and Python"
title = "Arcpy Mapping Demo:  Introduction to arcpy.mapping and Python interaction"
mxd = arcpy.mapping.MapDocument(doc)
mxd.author = author
mxd.description = description
mxd.title = title
mxd.relativePaths = True

df = arcpy.mapping.ListDataFrames(mxd)[0]   # list of data frames, 1 exists by default
df.name = "Sample files"                    # set its title
mxd.activeView = df.name                    # activate it

for shp in shp_files:                       # cycle through the list of shapefiles
  #fn, ext = os.path.splitext(f)            # for testing
  lyr = arcpy.mapping.Layer(shp)            # add the files and auto arrange
arcpy.ApplySymbologyFromLayer_management(lyr,lyr_files[1])  # apply symbology from lyr files
#arcpy.mapping.UpdateLayer(df, updateLayer, sourceLayer, True) 
del template, shp_files, lyr_files, lyr, df, mxd
del doc
| improve this answer | |
  • Thanks so much for all the detail! I had high hopes here, and I definitely needed some of this information for my later plans with the script. However, I am still getting the same error in the same place: the line: "lyr = arcpy.mapping.Layer(shp)" the error: valueError: Object: CreateObject Layer invalid data source – gisuser Jan 27 '15 at 23:20
  • try... arcpy.env.workspace = "C:/test/" ...with the extra / ... my example was just a sample...and obviously you dont have my data, so you will have to change them to reference your data...I was demonstrating what could be done. in that example, i had shapefiles stored in a folder relative to mxd_src which were used in the blank template mxd, from there symbology was applied using the lyr files and the mxd saved then ... with any luck arcmap was started with everything 'automagically' there – user681 Jan 28 '15 at 0:44
  • Indeed, I changed the directory and file names of course. I also added some test code as shown in my original post to ensure that the files existed (using arcpy.Exists()) just to make sure I got all the filepath/workspace variables correct. Still got the same error. – gisuser Jan 29 '15 at 2:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.