-1

I need to add all features within a dataset called MainSt in a file geodatabase which is stored at following directory

C:/Temp/Roads.gdb

to current map. using following code I am able to add them one by one but can you please let me know how I can loop and add them dynamically

    mxd = arcpy.mapping.MapDocument("CURRENT")
    df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
    targetGroupLayer = arcpy.mapping.ListLayers(mxd, "Main Streets", df)[0]
    addLayer = arcpy.mapping.Layer(r"C:\Temp\Roads.gdb\MainSt\trace_Fittings")
    arcpy.mapping.AddLayerToGroup(df, targetGroupLayer, addLayer, "BOTTOM")
    arcpy.RefreshActiveView()
    arcpy.RefreshTOC()
  • 1
    why is this question so downvoted? – ziggy May 25 '17 at 1:30
  • Seriously?! why some people like to just down vote questions without any help or hint! – user1106951 May 25 '17 at 4:24
  • 1
    @ziggy The down-vote option gives a reason - "This question does not show any research effort; it is unclear or not useful". I'm not saying that's why in this case, but it is a reason to downvote. – Midavalo May 25 '17 at 4:35
  • 1
    @user1106951 I'm unsure what you mean by "without any help or hint" as there are two answers already? – Midavalo May 25 '17 at 4:35
4

Take a look at arcpy.ListFeatureClasses() and how that works in a `for loop. See the Code Sample at the bottom of that page.

Then as you loop through the feature classes you just use your same code, with addLayer pointing at each feature class in the loop.

arcpy.env.workspace = r"C:\Temp\Roads.gdb\MainSt"

mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
targetGroupLayer = arcpy.mapping.ListLayers(mxd, "Main Streets", df)[0]

fcs = arcpy.ListFeatureClasses()
for fc in fcs:
    addLayer = arcpy.mapping.Layer(fc)
    arcpy.mapping.AddLayerToGroup(df, targetGroupLayer, addLayer, "BOTTOM")
arcpy.RefreshActiveView()
arcpy.RefreshTOC()

All I have changed in your code is to add the arcpy.env.workspace, arcpy.ListFeatureClasses(), and the for loop, then re-point your feature class to the looped fc.

0

I think your first step will be to determine how to create a list of feature classes in a particular feature dataset.

Once you have that you can use a for loop to iterate through it.

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.