Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I want to add a shapefile to an mxd document using arcpy but it generates the following error when used by adding script in arctoolbox

import arcpy
mxd = arcpy.mapping.MapDocument("CURRENT")
dataFrame = arcpy.mapping.ListDataFrames(mxd, "*")[0] 
addLayer = arcpy.mapping.Layer(r"D:/Data/input/Line.shp")
arcpy.mapping.AddLayer(dataFrame, addLayer)

ERROR--------------

<type 'exceptions.ValueError'>: Object: CreateObject Layer invalid data source
Failed to execute (Script).

Thanks in advance

share|improve this question
1  
Are you sure that D:/Data/input/Line.shp exists? Have you tried addLayer = arcpy.mapping.Layer(r'D:/Data/input/Line.shp')? –  Stev_k Mar 30 '12 at 13:49
    
yes file exist and single cote also not work –  Mak Pak Mar 30 '12 at 13:54
    
Your drive is "D" and not "C"? Can you try to load a different shapefile? Are you current on your service packs? –  artwork21 Mar 30 '12 at 13:58
    
yes service packs are ok - lyr file work fine but shp file generates error –  Mak Pak Mar 30 '12 at 14:02
add comment

2 Answers

I tested your snippet (at least in ArcMap's interactive Python window) and got the same error until I changed the formatting of the string parameter to the Layer() method. Either single or double quotes work, but I had to use forward slashes, not backslashes, and no leading 'r'. Like:

addLayer = arcpy.mapping.Layer('C:/path/to/shapefile.shp')

or

addLayer = arcpy.mapping.Layer("C:/path/to/shapefile.shp")

Good luck!

share|improve this answer
    
thanks , but code not work for shp file for lyr it works and i used extra function of arcpy.MakeFeatureLayer_management to convert shp to lyr . now it works for me –  Mak Pak Mar 30 '12 at 15:54
    
no, I know the API examples show use of *.lyr file, but what I show above most definitely works with a shapefile or other data source, I took your snippet exactly and only modified the string argument as shown and it ran successfully. –  MC5 Mar 30 '12 at 16:00
    
thanks anyway but not working for me, and i donot the reason –  Mak Pak Mar 30 '12 at 16:29
add comment

You need add into argument of Layer class the "lyr_file_path". Layer() class accepts *.lyr file!

Can you try with layer (*.lyr) file?

share|improve this answer
    
yes it works for lyr –  Mak Pak Mar 30 '12 at 15:55
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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