0

I'm trying to write a code for automating changing the source for some layers of a mxd document. I have three layers that should point to the same shapefile, they are only displayed with different symbology in the map. So, here is a version of what I tried:

#in this example, the shapefile I want is "C:\\Users\\USER_NAME\\folder\\new_shape.shp"
#this new shapefile IS NOT in the same directory as the previous one
#also, I tried first changing only one layer

import arcpy
mxd = arcpy.mapping.MapDocument('current')
principal = arcpy.mapping.ListDataFrames(mxd)[0]

lyr1 = arcpy.mapping.ListLayers('current', '', principal)[5]
lyr2 = arcpy.mapping.ListLayers('current', '', principal)[6]
lyr3 = arcpy.mapping.ListLayers('current', '', principal)[7]

lyr1.replaceDataSource("C:\\Users\\USER_NAME\\folder", "SHAPEFILE_WORKSPACE", 'new_shape')

From all the examples I found, this should do the trick. However, when I open the MXD, the layer's datasource is the same as before. This happens for any of the three layers.

I really couldn't figure out what is wrong in this code.

I'm using ArcGIS 10.5 and Python 2.7

3
  • 1
    You don't seem to have saved the changes (at least, it's not in your code). Not uncommon; in fact, this is a duplicate of a (probably closed) question from a few months back.
    – Vince
    Commented Dec 14, 2021 at 17:53
  • You say, using mxd.save()? I didn't add it to this sample of code here, but I have used it. Commented Dec 14, 2021 at 18:20
  • Well, since you don't specify the validate parameter, the default value of True is used, which is documented as "If set to True, a workspace will only be updated if the workspace_path value is a valid workspace. If it is not valid, the workspace will not be replaced. If set to False, the method will set the source to match the workspace_path, regardless of a valid match. In this case, if a match does not exist, then the data source would be broken." so your replacement is incorrect in some way. Not including the .shp suffix could be a cause.
    – Vince
    Commented Dec 14, 2021 at 18:56

1 Answer 1

0

Someone from outside StackOverflow was able to help me, so I will share the solution, which was quite simple.

Adding '\\' to the end on my folder path made everything work fine for me!

I really have no idea why, since I haven't seen this in any of the examples I could find online, though.

But adding the .shp suffix to the shapefile name returns a ValueError, so ajusting only the path is the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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