python,  developer,  arcgis desktop

ArcMap Layers to LYR Files with Python

ArcMap Layers to LYR Files with Python

A tiny Python script to show how to export ArcMap Layers to LYR Files with Python. Although it’s a short script, it shows how easy it is to use Python with ArcPy to jump into ArcMap layer properties. To add some variation, we will only export layers that sit at the root level of the map’s table of contents. The child layers are still exported inside their parent LYR file.

Requirements

Pretty basic requirements for this task and based on using almost any version of ArcGIS 10.x (tested on 10.3.1 and 10.5). The goal is to export LYR files by looping through the table of contents. We need the Python OS module for easy access to some path options - this isn’t required, but makes life easy. Second, the ArcPy module is required to read the Map document (MXD) contents.

As mentioned earlier, we could export every layer, including all child layers. Most of the time it seems like people are looking to accomplish one of the following:

  1. Export just the Layers that have data, and none of the group layers. This means we would export single layers, or the deepest children of group layers (could have a group of groups with layers, etc). Small changes to the code below would be required for this approach.
  2. Export just the layers at the root level of the table of contents. This could be a single layer of data, or a group layer. Saved group layers do include the details about the children layers. This is the requirement and approach that will be used in this code example.

How can we determine if we are at a root level? Line 17 in the code below checks if the layer.name value is equal to the layer.longName value. If they are equal, it’s a root level layer (group or stand-alone).

Long Name Property: This property is valuable when trying to determine whether a layer belongs to a group layer. If a layer does not belong to a group layer, the long name will equal the layer name. If a layer does belong to a group layer, the group layer structure will be included in the long name. For example, the name of a layer nested inside a group layer within another group layer may look something like Group1\Group2\LayerName. All layer types support this property. ~ Esri help on the longName property.

The Code: ArcMap Layers to LYR Files with Python

Commenting inside the code sample will help explain most of of the details. One of the optional pieces included is to find and replace some text characters. In the Windows OS, there are a list of illegal characters that can’t be used in file or folder names. Since the LYR file name is set to be the same as the Layer Name in the Map, best to trap some of these in advance (see line 18 and 19 for some basic find/replace examples).

Happy coding.


If you found my writing entertaining or useful and want to say thanks, you can always buy me a coffee.
ko-fi