1

I have code like this from Xander Bakker

def main():
    import arcpy
    fc = r'Drive:\Path\To\Source\FC'
    fld_seq = 'SequenceLbl'

    # Add field if it does not exist already
    AddField(fc, fld_seq, "TEXT", 12)

    # start update cursor to update the values in the new field
    flds = (fld_seq)
    cnt = 0
    with arcpy.da.UpdateCursor(fc, flds) as curs:
        for row in curs:
            cnt += 1
            km, hect = divmod(cnt, 10)
            hect_txt = "%03d" % (hect * 100,)
            lbl = "{}+{}".format(km, hect_txt)
            print cnt, hect_txt
            curs.updateRow((lbl, ))


def AddField(tbl, fld_name, fld_type, fld_length):
    if len(arcpy.ListFields(tbl, fld_name)) == 0:
        arcpy.AddField_management(tbl, fld_name, fld_type, None, None, fld_length)

if __name__ == '__main__':
    main()

the result will show 0+100 0+200 0+300 .. 0+900 1+000 1+100 and so on..

I want to start from 0+000 instead of 0+100, what code do I need to add or modify from that code?

  • move the statement cnt += 1 to the end of the for loop? – JimT Nov 15 '18 at 11:32
  • The other alternative is to change the variable initialization to -1, so the pre-increment results it zero on the first pass. I can't recommend changing code you don't understand, especially if you don't have the correct indentation. – Vince Nov 15 '18 at 12:02
1

From the comments there are two options.
As commented by JimT move the variable incrementing statement to the end of the for loop:

# start update cursor to update the values in the new field
flds = (fld_seq)
cnt = 0
with arcpy.da.UpdateCursor(fc, flds) as curs:
    for row in curs:
        km, hect = divmod(cnt, 10)
        hect_txt = "%03d" % (hect * 100,)
        lbl = "{}+{}".format(km, hect_txt)
        print cnt, hect_txt
        curs.updateRow((lbl, ))
        cnt += 1

Or, as commented by Vince, modify the initialisation of the cnt variable:

# start update cursor to update the values in the new field
flds = (fld_seq)
cnt = -1
with arcpy.da.UpdateCursor(fc, flds) as curs:
    for row in curs:
        cnt += 1
        km, hect = divmod(cnt, 10)
        hect_txt = "%03d" % (hect * 100,)
        lbl = "{}+{}".format(km, hect_txt)
        print cnt, hect_txt
        curs.updateRow((lbl, ))

Be aware - code snippets might not follow your indentation.

  • Thanks guys.. solved already.. just change the cnt = 0 to cnt = -1 – Rudini Nov 16 '18 at 12:03

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.