As part of a larger script, I have code that checks to see if a particular field exists. If not, it creates it and calculate its area. The script works just fine until it goes to calculate the area of the newly created field, where it gives me KeyError: '#'. Is this error because the field was just created? If so, how do I work around it?
I am running Python 3.6 with PyCharm.
Here is the code I am having issues with--"projArea" is the project area feature class.
# Test to see if there is an "Acres" field in the Project Area FC.
projFields = arcpy.ListFields(projArea) # List of fields in project area fc
x = False # Default condition is that the field doesn't exist
for f in projFields:
if f.name == "Acres": # If there is a field named "Acres"
x = True
if x is not True: # If none of the fields are named "Acres"
arcpy.AddMessage("{} does not have an Acres field. Creating field.".format(projArea))
arcpy.AddField_management(projArea, 'Acres', 'DOUBLE') # Create the field
arcpy.AddMessage("Calculating area.")
arcpy.management.CalculateGeometryAttributes(projArea, 'Acres', area_unit="ACRES") # Calculate the area
arcpy.AddMessage("Area calculated.")
Any help would be appreciated.
Solved! Go to Solution.
Replace
arcpy.management.CalculateGeometryAttributes(projArea, 'Acres', area_unit="ACRES")
With arcpy.management.CalculateGeometryAttributes(projArea, [["Acres", "AREA"]], area_unit ="ACRES")
["Left", "EXTENT_MIN_X"]
in your case
[projArea, 'AREA']
Calculate Geometry Attributes (Data Management)—ArcGIS Pro | Documentation
a list is required for the first parameter, the field name and the property
Replace
arcpy.management.CalculateGeometryAttributes(projArea, 'Acres', area_unit="ACRES")
With arcpy.management.CalculateGeometryAttributes(projArea, [["Acres", "AREA"]], area_unit ="ACRES")
What Dan and Davin said.
Plus, you can just do this:
#projFields = arcpy.ListFields(projArea)
#x = False
#for f in projFields:
# if f.name == "Acres":
# x = True
projFieldNames = [f.name for f in arcpy.ListFields(projArea)] # extract field names
x = "Acres" in projFieldNames # Test if field "Acres exists
That worked! I *knew* it was something that was staring me in the face. Thank you, all!