Sunday 16 July 2017

arcpy - Using Python Script tool in ModelBuilder to check if field exists, if not, create one?


I'm trying to create a script tool to use in ModelBuilder that will check the incoming dataset for the existence of a particular field. If the field exists it should simply go on to the next calculate field tool which will use that field, however if the field doesn't exist it should create it before running the next calculate field tool so that I don't get an error from the Calculate field tool, because the field it's trying to use doesn't exist.


I added this script to the ModelBuilder, but it keeps giving me the same error as when I try to run the model and the field doesn't exist. So the script tool is apparently not doing its desired job. Can anyone see an issue with my code? Is there a better way of trying to do this


ModelBuilder


# Import modules
import arcpy
import sys

import traceback

# Set local variables
indata = arcpy.GetParameterAsText(0)
fieldName = "PrintKey_GIS"

try:
# check if the PrintKey field exists
if arcpy.ListFields(indata, fieldName): #if field exists, evaluates to true
arcpy.AddMessage("PrintKey_GIS field exists")


else:
# Add a new field of that name
arcpy.AddField_management(indata, fieldName, "TEXT", "", "",25, "PrintKey_GIS" , "NULLABLE", "", "",)
arcpy.AddMessage("PrintKey_GIS field does not exist")

except Exception as e:
arcpy.AddMessage(arcpy.GetMessages())


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...