0

I have a bunch of folders which all have (almost) identical folder structures and file geodatabases of identical structures which in this folder structure. I need to add all of the same type of feature class to an mxd and merge them into a new feature class. There are a lot of them so I thought this seemed like the sort of thing I could do in python.

The folders are all in the same folder and there is a common path to the feature class in question, for example:

project_name/Subfolder1/subfolder2/project_name.gdb/featuredataset/featureclass.

so I'm thinking of trying to loop through the folders and extraxt the feature class from each of them using a method like this, but I'm not quite sure how arcpy interacts with, and loops through windows folders.

Since I'm looking for any feature class of this name within the root folder could I use a more brute force method that searches in the root folder and subfolders for the name and adds it to the mxd?

  • It seems that adding the FC's to a .mxd is an unnecessary step. Could this step be eliminated if all of the files were located and merged directly? – Aaron Feb 28 '14 at 14:11
2

Edit: Something a little more robust than my notepad outline:

Method one: List the directories in the root folder and slap the suffix on the end.

Method two: Use os.walk to go through the folders

import arcpy
import os

arcpy.env.workspace ="in_memory"
project = "c:\\Users\\roo\\Desktop\\project_name"
suffix = "test.gdb\\test_verts"

# setup mxd and map document
MAP = project + "\\Untitled.mxd"
mxd = arcpy.mapping.MapDocument(MAP)
df = arcpy.mapping.ListDataFrames(mxd, "*")[0]

# method one
for folder in os.listdir(project):
    if os.path.isdir(folder):
        fc = os.path.join(project, folder, suffix)
        if arcpy.Exists(fc):
            lyr = os.path.basename(fc) + "_" + folder
            arcpy.MakeFeatureLayer_management(fc, lyr)
            addLayer = arcpy.mapping.Layer(lyr)
            arcpy.mapping.AddLayer(df, addLayer, "BOTTOM")
mxd.save()

# method two
for dirpath, dirnames, filenames in os.walk(project):
    for dirs in dirnames:
        fc = os.path.join(project, dirs, suffix)
        if arcpy.Exists(fc):
            lyr = os.path.basename(fc) + "_" + dirs
            arcpy.MakeFeatureLayer_management(fc, lyr)
            addLayer = arcpy.mapping.Layer(lyr)
            arcpy.mapping.AddLayer(df, addLayer, "BOTTOM")
mxd.save()
  • If @whatahitson were using ArcGIS 10.1 SP1 or later then arcpy.da.Walk would be useful here. – PolyGeo Feb 27 '14 at 21:56
  • You should wrap your layer creation and adding the layer to the mxd with a try...except block, just in case you encounter a corrupt dataset. – blord-castillo Feb 28 '14 at 14:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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