Add layer from current folder

268
6
11-20-2017 07:02 PM
Mohd_NurhafiziSaidin
New Contributor II

Hye everyone,

I have create one Python file, the task is to add layer from the latest or current folder following date of folder. The sample folder is below;

Sample of folder

This is my sample code on Python;

import arcpy
import os

# suppose you want to add it to the current MXD (open MXD)
mxd = arcpy.mapping.MapDocument(r"C:\Users\User\Documents\MTSB_JPS\MXD\test.mxd")
dataFrame = arcpy.mapping.ListDataFrames(mxd, "*")[0]

# base folder
workspace = r"C:\Users\User\Documents\MTSB_JPS\Flood_Forecasting_Outputs\TRN"
walk = arcpy.da.Walk(workspace, topdown=False, datatype="FeatureClass")

for dirpath, dirnames, filenames in walk:
    for filename in filenames:
        layerfile = os.path.join(dirpath, filename)
        addlayer = arcpy.mapping.Layer(layerfile)
        arcpy.mapping.AddLayer(dataFrame, addlayer, "BOTTOM")
        mxd.save()

arcpy.RefreshTOC()
arcpy.RefreshActiveView()
del addlayer, mxd

The problem is, this code can't add the layer from the latest or current folder. It should add the layer from "20171117_0600_AF" but when I run this code, it add the layer from "20170701_2000_AF" folder.

Please help.

Tags (2)
0 Kudos
6 Replies
DanPatterson_Retired
MVP Esteemed Contributor

is topdown=False correct?

have you put in some print statements to see what is being returned at each step in the loops?

Mohd_NurhafiziSaidin
New Contributor II

Hye Dan,

Yups..topdown is correct. The result of print statements is below;

print output of loop

How I want add the shapefile from the last folder, thats mean the bottom of printout. Because in this root folder, the folder with date will be update with the new folder following by date. My task is to pick up the latest folder (CURRENT date) that contain the shapefile.

Thank you.

0 Kudos
DanPatterson_Retired
MVP Esteemed Contributor

I guess I am not seeing the desired outcome list versus the list in the way they are being added.  If it is a matter of the order in which they are added, it could a sorting issue 

Mohd_NurhafiziSaidin
New Contributor II

Thanks Dan 

Yups..it's a sorting issue. On progress to solve the debugs. 

0 Kudos
RebeccaStrauch__GISP
MVP Esteemed Contributor

On a quick look, to me it looks like the for loops are going to try to add all layers.  Maybe you can grab date part of the name and do a compare until you find the latest?  Or it if it will always be the last item on the list, get a count and try to grab that.  Just a few things to try. 

Mohd_NurhafiziSaidin
New Contributor II

Thanks Rebecca.

For now, I try to using combination of loop and sorting. Let's see how it goes and if it doesn't, we'll try something else.

0 Kudos