Select to view content in your preferred language

Script to loop through Multiple Datasets

1553
5
02-17-2022 03:20 PM
SteveKim1
Emerging Contributor

Hi Everyone,

Is there a script where I can run through multiple datasets in a gdb. 

For example: I want to add fields to every feature class  which is grouped in their respective datasets. 

Thanks!

0 Kudos
5 Replies
AlfredBaldenweck
MVP Regular Contributor

Yup, there is. See here ListFeatureClasses—ArcGIS Pro | DocumentationListDatasets—ArcGIS Pro | Documentation

arcpy.env.workspace = [whatver your workspace is]
FClist = arcpy.ListFeatureClasses()
for FC in FClist:
    code
    code

#if using data sets
arcpy.env.workspace = [whatver your workspace is]

FDList = arcpy.ListDatasets()
for FD in FDList:
    FClist = arcpy.ListFeatureClasses()
    for FC in FClist:
        code
        code

 

0 Kudos
SteveKim1
Emerging Contributor

Thanks Alfred for the script! When I use the second script to loop through the Datasets and then through each Feature Class, the ListFeatureClasses() function is not returning any values. Here's my script below:

SteveKim1_0-1645199794970.png

Did I miss any steps or anything wrong with this code?

 

Thanks!

 

0 Kudos
AlfredBaldenweck
MVP Regular Contributor

Oops, it looks like I should have read the documentation more closely.

What happened was that ListFeatureClasses just grabs everything from the workspace, ignoring the stuff in datasets, unless you specify that you want the stuff in the datasets.

You may also want to try out Walk(), like Joshua suggested.

arcpy.env.workspace =  r'=...\Data_Transfers.gdb'

field1 = "LATITURE" #These are mispelled
field2 ="LONGITURE"#These are mispelled

FDlist = arcpy.ListDatasets(feature_type='feature') #The parameter in here isn't strictly necessary
print(FDlist)
'''if you want to include all feature classes, regardless of wheteher they're in a dataset.'''
#FDlist = [''] + FDlist if FDlist is not None else [] 

for FD in FDlist:
    FClist= arcpy.ListFeatureClasses(feature_dataset = FD)
    for FC in FClist:
        print(FC)
        if not (field1 in arcpy.ListFields(FC) and (field2 in arcpy.ListFields(FC))):
            FC = arcpy.management.AddField(FC, field1, "DOUBLE",field_alias = "Lat")
            FC = arcpy.management.AddField(FC, field2, "DOUBLE",field_alias = "Long")

 

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

Use Walk—ArcGIS Pro | Documentation, much more Pythonic than the older List functions.  The documentation has some working examples.

0 Kudos
AlfredBaldenweck
MVP Regular Contributor

Oooh, I had no idea this existed. Thanks, I'll have to try this out!

0 Kudos