1

I have the following script, to calculate the area of a shapefile on a given field in its attribute table.

import arcpy
shapefile = r"path/shapefile.shp"
# Add SUP_HA field
arcpy.AddField_management(shapefile, "SUP_HA", "DOUBLE", 10, 2, "", "refcode", "NULLABLE", "REQUIRED")
# Calculate area in hectares and update SUP_HA field
with arcpy.da.UpdateCursor(shapefile, ["SHAPE", "SUP_HA"]) as cur:
 for row in cur:
 # Get geometry of shapefile
 geom = row[0]
 # Calculate area in hectares
 area_ha = geom.area / 10000 # 1 hectare is equal to 10000 square meters. Change the calculation in this line if geom.area is not in square meters
 # Update SUP_HA field with calculated area
 row[1] = area_ha
 cur.updateRow(row)

When I run the script I get the following error:

Traceback (most recent call last): File "path/script.py", line 10, in for row in cur: UnicodeDecodeError: 'utf8' codec can't decode byte 0xf3 in position 35: invalid continuation byte

The error occurs in the "for row in cur" loop. Any solution?.

I have investigated, but I have not found anything to fix it. This script is made in Python 2.

PS: Comment that it adds the field, but the calculation of the surface does not.

asked Dec 26, 2022 at 15:16
4
  • 1
    Try replacing shapefile = "path/shapefile.shp" by shapefile = r"path/shapefile.shp" Commented Dec 26, 2022 at 15:26
  • That's it, I'll edit my question. Commented Dec 26, 2022 at 15:32
  • 1
    You need to use the Shape token, SHAPE@, for your field and not the word "SHAPE" since the latter does not return a geometry object. Commented Dec 26, 2022 at 16:56
  • Using SHAPE@ instead of "SHAPE" worked for me! Commented Dec 26, 2022 at 18:36

1 Answer 1

1

Maybe you can try this out when reading your file:

import arcpy
shapefile = r"path/shapefile.shp" <-- use raw string
shp = shapefile.decode('iso-8859-1').encode('utf8') # <-- try to add this line
# or shp = shapefile.encode('utf8')

The rest is left unchanged. You can also test by replacing iso-8859-1 by latin-1.

Also, I highly suggest you to migrate to Python 3 if possible.

This may also help you as it's probably an encoding/decoding issue with your file:

answered Dec 26, 2022 at 15:34

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.