I just started to code in Python and have a problem with this code. I am trying to verify a field type, and after that, if the value returns false, add a new field and calculate.

The problem is: every time I run the script a new field is added even if the condition is True.

How can I solve this?

import arcpy

Base = "PATH"

fields = arcpy.ListFields(Base)

for field in fields:

    if field.name == 'TEST' and field.type == "Float":
       Field_Name = "TEST2" 
       Field_Type = "FLOAT"
       Field_Name__2_ = "TEST2"
       Expression = "!CODE!"

       Output_Feature_Class = Base

       arcpy.AddField_management(Base, Field_Name, Field_Type, "", "", "", "", "NULLABLE", "NON_REQUIRED", "")

       Output_Feature_Class = Base

       arcpy.CalculateField_management(Output_Feature_Class, Field_Name__2_, Expression, "PYTHON_9.3", "")
  • Stephen, this code works well in ArcGIS. Can you tell me what`s wrong? Although I put some indents in the code. see it looks better – vcruvinelr Jun 23 '17 at 1:53

To detect if your field is present you can do something like:

have_test_field = sum(
    field.name == 'TEST' and field.type == "Single"
    for field in fields)

if not have_test_field:
    # add the field here
  • Stephan, thank you very much! With your suggestion the code works very well. Problem Solved! – vcruvinelr Jun 23 '17 at 2:22
  • I`m a new user. many thanks again to explain how the site works. Regards! – vcruvinelr Jun 23 '17 at 2:26

"Float" in arcpy is defined as "Single", thus you need to change the code the following lines as follws:

for field in fields:
    if field.name == 'Test' and field.type == "Single":

You can refer to the Field help. I will quote the following:

The field type:
Blob —Blob
Date —Date
Double —Double
Geometry —Geometry
GlobalID —Global ID
Guid —Guid
Integer —Integer (Long Integer)
OID —Object ID
Raster —Raster
Single —Single (Float)
SmallInteger —Small Integer (Short Integer)
String —String (Text)
  • Ahmad, I appreciate your comments! I didnt remember this detail. the code from Stephan works well. I tried with your suggestion but it add the field always. In time...You are the autor from the Udemys Python course? if you, i did you course last week! Congrats, it`s started my interest with Python. – vcruvinelr Jun 23 '17 at 2:24
  • @ViniciusCruvinel Strange. When I tested the code in my answer, it didn't add any field because the conditions were met. Anyway, I am glad the problem was solved. – ahmadhanb Jun 23 '17 at 2:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.