Tuesday 20 August 2019

arcpy - Python Script to Add Fields to Feature Classes


I have to try to add a field called 'Name' to a bunch of different feature classes using python, and then access the name of the feature class to fill in the field. I have no idea how to even start this! I know I need a loop but that's all I know.



Answer



Here is a cursor-based approach, which I usually default to as syntax is simpler than using Calculate Field. This is the workflow:


import your module


import arcpy


Set the workspace so that Python knows where to look for the feature classes. In this case, it is a GDB


arcpy.env.workspace = r'C:\temp2\my_gdb.gdb'

Start a loop and iterate over the feature classes in the GDB


for fc in arcpy.ListFeatureClasses():

Add a text field called "Name" of length 50


arcpy.AddField_management(fc, "Name", "TEXT", field_length = 50)


Within each feature class attribute table, write the name of the current FC


with arcpy.da.UpdateCursor(fc, "Name") as cursor:
for row in cursor:
row[0] = fc
cursor.updateRow(row)



import arcpy

arcpy.env.workspace = r'C:\temp2\my_gdb.gdb'


for fc in arcpy.ListFeatureClasses():
arcpy.AddField_management(fc, "Name", "TEXT", field_length = 50)
with arcpy.da.UpdateCursor(fc, "Name") as cursor:
for row in cursor:
row[0] = fc
cursor.updateRow(row)



enter image description here



No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...