2

I am trying to use python to remap a set of layer files in a group layer (not within an mxd) but am unable to create a layer object for them so I can use replaceDataSource. One of my group layers is

C:\Workspace\LayerFiles\Administration.lyr

I've attempted to use arcpy.mapping.Layer with the following paths:

C:\Workspace\LayerFiles\Administration.lyr\Ownership.lyr C:\Workspace\LayerFiles\Administration.lyr\Ownership C:\Workspace\LayerFiles\Administration\Ownership.lyr C:\Workspace\LayerFiles\Administration\Ownership

which all come up with ValueError: Object: CreateObject Layer invalid data source

Is there no way to get a direct path to layers within a group layer? If that's the case is there another means to create a layer object for each one within a loop? Hopefully there's a simple answer, but my search has come up empty so far.

2

1 Answer 1

2

There isn't a layer file within another layer file. It's just a layer object that contains multiple layer objects. The 'isGroupLayer' property tells you whether it is a group layer or not. You can iterate through them and change the source like so:

import arcpy

group_layer = arcpy.mapping.Layer('C:\\Workspace\\LayerFiles\\Administration.lyr')
for layer in group_layer:
    if layer.name == 'Ownership':
        layer.replaceDataSource('C:\\Path\\To\\New\\Source',
                                'SHAPEFILE_WORKSPACE', # Or whatever type of workspace
                                'New_Source')

# Overwrite the old layer file
group_layer.saveACopy('C:\\Workspace\\LayerFiles\\Administration.lyr')

Also, make sure you are using double backslashes on your file paths in Windows.

2
  • Thanks. I was able to get it to work by looping it like this. I usually just drop an "r" in front of my path strings. Is there an advantage to using double backslash vs. raw text?
    – Luke
    Dec 5, 2016 at 20:36
  • I was using raw strings for a while, but there was a scenario where it didn't work like I expected, so I've been using double-backslashes ever since. They should theoretically evaluate the same though.
    – agarfield
    Dec 6, 2016 at 6:24

Your Answer

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

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