1

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
arcpy.mapping.Layer("shapefile.shp")

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
arcpy.MakeFeatureLayer_management("shapefile.shp","myshapelayer")

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.

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
gisuser
  • 23
  • 5
  • 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
  • This answer from the duplicate has the technique that I think should work at 10.0 - http://gis.stackexchange.com/a/12538. I think the one you are trying had a bug that was fixed at 10.1 SP1. – PolyGeo Jan 23 '15 at 23:31
  • I found that link several hours ago, and tried it to no avail. This line: newlayer = arcpy.mapping.Layer(path_to_shapefile_or_feature_class) gives an error. – gisuser Jan 23 '15 at 23:32
  • put: putputarcpy.env.workspace = "in_memory" on the line after: import arcpy – gm70560 Jan 23 '15 at 23:32
  • What precise code did you run? What precisely was the error you received from that code? In your question I can only see you trying the other way. – PolyGeo Jan 23 '15 at 23:33
  • may be worth setting your workspace to the folder that contains the shapefile: arcpy.env.workspace = r"Z:\program..." and then you just put "shapefile.shp" as the first parameter? – mr.adam Jan 23 '15 at 23:35
  • Have tried that as well mr.adam – gisuser Jan 23 '15 at 23:36
  • @PolyGeo I copied out more of the code for you, hope it helps? – gisuser Jan 23 '15 at 23:41
  • Your current code snippet does not include setting your workspace via arcpy.env.workspace prior to trying to use a shapefile from it without the full path being specified. Unfortunately, I do not have 10.0 to test your code. – PolyGeo Jan 23 '15 at 23:46
  • My code snippet is currently displaying for me as having set arcpy.env.workspace - perhaps reload the page or something? – gisuser Jan 23 '15 at 23:48
  • Placing a shapefile in "C:/Python27/ArcGISx6410.2" seems like a very risky thing to do - try copying it to a simple location like C:\temp as a test. Also, what is your precise operating system? It sounds like you may need to double-check your configuration against the System Requirements for 10.0. – PolyGeo Jan 23 '15 at 23:49
  • Noted, agreed, and I just tried your suggestion - same procedure (with the new path of course), same error. As to the OS: Windows Server 2012 Standard, and I also tested this code on a linux installation (don't know what the exact installation was) and received the same error. – gisuser Jan 23 '15 at 23:55
  • I'll re-open this question to see if anyone will post an Answer. I'll try to get back and test it - for some reason I thought you were using 10.0 but it seems to be 10.2 so I must have misread. – PolyGeo Jan 24 '15 at 00:15

3 Answers3

1

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")
MrBubbles
  • 833
  • 5
  • 15
  • 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 00: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 00: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
0

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

'''
mxd_create.py

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
ie
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"
shutil.copyfile(template,doc)

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.mapping.AddLayer(df,lyr,"AUTO_ARRANGE")     
arcpy.ApplySymbologyFromLayer_management(lyr,lyr_files[1])  # apply symbology from lyr files
#arcpy.mapping.UpdateLayer(df, updateLayer, sourceLayer, True) 
arcpy.RefreshActiveView()
mxd.save()
del template, shp_files, lyr_files, lyr, df, mxd
os.startfile(doc)
del doc
##
PolyGeo
  • 65,136
  • 29
  • 109
  • 338
  • 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
    –  Jan 28 '15 at 00: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 02:14
0

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.

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
gisuser
  • 23
  • 5