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.
1 Answer 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:
- https://stackoverflow.com/q/5552555/6630397
- https://stackoverflow.com/q/19699367/6630397
- https://community.esri.com/t5/python-questions/unicodedecodeerror-ascii-codec-can-t-decode-byte/m-p/555692
- https://community.esri.com/t5/python-questions/re-unicodedecodeerror-utf8-codec-can-t-decode-byte/td-p/483842
shapefile = "path/shapefile.shp"
byshapefile = r"path/shapefile.shp"
SHAPE@
, for your field and not the word "SHAPE" since the latter does not return a geometry object.