Select to view content in your preferred language

Iterate though folder and add lyrx to a map

2432
22
Jump to solution
08-02-2022 02:21 AM
by Anonymous User
Not applicable

I am working with a notebook in ArcGIS Pro and I want to add all .lyrx files within a local folder to a map.

I have set the workspace and created a list with:

 

arcpy.env.workspace = "path to my data"

list_layers = arcpy.ListFiles("*.lyrx")

 

which works fine. I have tried to create a for loop to iterate though the list and add the layers to the map in my current project without success.

 

I realise this is probably easy to do but I can't work it out. Any help would be greatly appreciated!

0 Kudos
22 Replies
by Anonymous User
Not applicable

You can see the the two produces the same results (change to your path):

import os
import arcpy
import glob

arcpy.env.workspace = r"C:\Users\...\Documents"

# Copy each file with a .csv extension to a dBASE file
for lyrx_file in arcpy.ListFiles("*.lyrx"):
    pth = os.path.join(arcpy.env.workspace, lyrx_file)
    print(f'List Files: {pth}')

for filename in glob.iglob(f'{arcpy.env.workspace}/*.lyrx'):
      print(f'glob: {filename}')

 

RhettZufelt
MVP Notable Contributor

I can't get either method to work unless I set the LayerFIle first, then it is working as I expect (and I have to append the path as suggested above).

This is working for me:

 

 

import os
aprx = arcpy.mp.ArcGISProject("CURRENT")
aprxMap = aprx.listMaps("Map")[0]
arcpy.env.workspace = r"C:\path\to\lyrfiles"

list_layers = arcpy.ListFiles("*.lyrx")

for layer in list_layers:
    insertLyr = arcpy.mp.LayerFile(arcpy.env.workspace + os.sep + layer)
    aprxMap.addLayer(insertLyr)

 

 

R_

by Anonymous User
Not applicable

Thanks

0 Kudos