ArcPy – Adding New Value in New Field

arcmaparcpycursorfields-attributes

I have a polyline feature class with this attribute table:

enter image description here

I need to get values without decimal numbers.

I created a new field called "newLength" and tried to insert the new values (whole numbers only) with this code:

import arcpy

# add new field
arcpy.env.workspace = "G:\desktop\Project\lyr\New File Geodatabase.gdb"
arcpy.AddField_management("dis", "newLength", "LONG")

fc = r"G:\desktop\Project\lyr\New File Geodatabase.gdb\dis"
with arcpy.da.UpdateCursor(fc, "Shape_Length") as cursor: # second argument = field name
    for row in cursor:
       newValue = '%.0f' % float(str(row).strip('[]')) # convert list to string

# add the new numbers to the new field
with arcpy.da.UpdateCursor(fc, "newLength") as cursor: # second argument = field name 
   for row in cursor:
      cursor.updateRow([newValue])

but the error is a new field with the same values in all rows:

enter image description here

whereas the second row is true and the first row is an error

Best Answer

You are only filling in the last value of "newValue" in all the rows. Try to modify it this way;

import arcpy

# add new field
arcpy.env.workspace = "G:\desktop\Project\lyr\New File Geodatabase.gdb"
arcpy.AddField_management("dis", "newLength", "LONG")

fc = r"G:\desktop\Project\lyr\New File Geodatabase.gdb\dis"


# add the new numbers to the new field
with arcpy.da.UpdateCursor(fc, ["Shape_Length", "newLength"]) as cursor: # second argument = field name 
   for row in cursor:
      newValue = '%.0f' % float(str(row[0]).strip('[]')) # convert list to string
      row[1] = newValue
      cursor.updateRow(row)

Related Question