Update Cursor for a list of shp

605
2
11-04-2018 07:41 PM
AriVillafuerte
New Contributor II

Hello,

I want to add the data source (path name) to each attribute table . All of them were compiled from many folders so it's quite important for us to keep track. I'm quite new to python and I'm having trouble applying the update cursor function to populate the path name into the attribute table of each layer. This is what I have so far and I'm getting the error of 'in_table' is not a table or a featureclass. So I understand the list named 'FeatureClasses' is not a valid input for the update cursor function. How can I fix the code so it iterates through each shp listed in my mxd?

mxd= arcpy.mapping.MapDocument (r"path.mxd") 

#List with all the shp in the mxd
FeatureClasses = arcpy.mapping.ListLayers (mxd) 

# Add a field to each shp
for fc in FeatureClasses():
    arcpy.AddField_management(fc, "Path", "TEXT", field_length = 250)

#Update attribute table with their pathnames
for fc in FeatureClasses:
    # pull out the shapefile name
    shpName = layer.dataSource
    # define update cursor
    with arcpy.da.UpdateCursor(FeatureClasses, ("Path")) as cursor:
        for row in cursor:
            # set Path to the shapefile name for each row
            row[0] = shpName
            cursor.updateRow(row)‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

I also tried this other code that I found online and shows no errors but the field 'Path' it's still blank. When I print the 'Test' list it's also blank.

Test = arcpy.ListFeatureClasses("*.shp")
print Test
[]

Test = arcpy.ListFeatureClasses("*.shp")
for calc in Test:
     # pull out the shapefile name
     shpName = os.path.abspath
     # define update cursor
     with arcpy.da.UpdateCursor(calc, ("Path")) as cursor:
         for row in cursor:
             # set 'Path' to the shapefile name for each row
             row[0] = shpName
             cursor.updateRow(row) ‍‍‍‍‍‍‍‍‍‍‍‍‍‍

Thanks in advance!

Tags (1)
0 Kudos
2 Replies
DanPatterson_Retired
MVP Emeritus

why do you need to use arcpy mapping in the first example?

in the second example you need to establish a workspace from the start

arcpy.env.workspace = r"C:\path\to\a_folder"

JoshuaBixby
MVP Esteemed Contributor

I think your second example is the better approach.  As Dan already pointed out, you will need to set the workspace before trying to list feature classes.  Also, you will need to use os.path.join to create a full path for the update cursor, and your use of os.path.abspath is incorrect.  Take a look at the code samples in ListFeatureClasses—Help | ArcGIS Desktop