0

I have tried examples from the GIS support website and many more, but I cannot figure out how to get a codeblock for a field calculation to work within ArcPy.

Part of my code is underneath, it is a continuation of a table being added (multiple calculate fields). However the earlier calculations do not use a codeblock, the last one does. As a side note to the codeblock section, wing.IDE will not let me indent the code further than this. I hope that that is not where it goes wrong

Codeblock:

Codeblock_for_geometry_10 = """
    def val:
    if [AFSPRAAK] = 'Huur' then
    val = 'D102'
    elseif [AFPSRAAK] <> 'Huur' then
    val = 'D101'
    end if
    """

Field calculation (RVB_geometry_9 being the previous calculation on the table):

RVB_geometry_10 = arcpy.CalculateField_management(RVB_geometry_9, "NIVEAU_3", "val", "VB", Codeblock_for_geometry_10)

The error I get: A field name was not found or there were unbalanced quotation marks.

As far as I can tell the quatation marks are correct and the fieldnames are aswel. I would like to learn what I am doing wrong here for future calculations.

2
  • I am not sure if this is the problem or not, but I think you should close the block with another """ three double quotes.
    – ahmadhanb
    Apr 10 '20 at 7:22
  • 1
    Ah, my apologies! I missed that out in the copy paste to the post. It is closed with another three """, I will adjust it now.
    – Remko
    Apr 10 '20 at 7:23
3

You seem to be mixing python and VB syntax (def is python). Stick to python.

Here's a python version:

code_block = """
def my_function(my_field):
    if my_field == 'Huur':
        return 'D102'
    else:
        return 'D101'
"""


result = arcpy.CalculateField_management(RVB_geometry_9, "NIVEAU_3", "my_function( !AFPSRAAK!)", "PYTHON", code_block)

A quick way to generate this is to run the Calculate Field tool from ArcMap, open the geoprocessing->results window, right click the result and select "Copy as python snippet".

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.