问题描述
我正在独自学习适用于ArcGIS(10.8)的Python(2.7)。我有这个问题:
编写一个脚本,该脚本将文本字段添加到名为roads.shp的要素类中 FERRY并根据需要填充YES和NO值,具体取决于 FEATURE字段的值。
试图弄清楚并检查互联网后,我得到了这个脚本:
from arcpy
from arcpy import env
env.workspace = "C/esriPress/Python/Data/Exercise07/Results" # Set workspace
env.overwriteOutput = True # overwriting outputs
fc = "roads.shp" # input feature class
newfield = "FERRY" # new field to be created
fieldtype = "TEXT" # type of the field that is going to be created
fieldname = arcpy.ValidateFieldName(newfield) # to determine whether a specific name is valid or not
field_length = 3 # Lenght of th new field to be created
fieldlist = ListFields(fc) # list the fields in 'fc',it returns a reference number of each object,not the object name.
fieldnames = [] # Create an empty list
# Check whether 'newfield' already exist or not; if not,create it
for field in fieldlist: # For each element in 'fieldlist'...
fieldnames.append(field.name) #...add in the empty list 'fieldnames' the field name
if fieldname not in fieldnames: # if 'fieldname' don't exists in 'fiednames'...
arcpy.AddField_management(fc,fieldname,fieldtype,field_length) # ...Create 'fieldname' in 'fc' with length = 3
print ("New field has been added")
else:
print ("Field name already exists.")
# Search in the one field and update other field
fields = ['FEATURE',newfield] # Create a list that contains the field we apply condition,and the field we going to update
with arcpy.da.UpdateCursor(fc,fields) as cursor: # Setting the cursor; notice the cursor is made up of two fields
for row in cursor: # For each row in cursor...
if row[0] == "Ferry Crossing": #...if row in field 1 = "Ferry Crossing'...
row[1] = "YES" #... Set that row in field 2 to 'Yes'
else: # Otherwise...
row[1] = "NO" # ....Set that row in field 2 to 'No'...
cursor.updateRow(row) # Update cursor
print ("New field has been added" % newfield)
else:
row[1] = "NO"
cursor.updateRow(row)
print ("Field name already exists" % newfield)
但是,当我在PythonWin 2.7.16中运行脚本时,出现以下错误消息:
Failed to run script - syntax error - invalid syntax
我的脚本有什么问题?这是正确的方法吗?
解决方法
似乎您有2个else
块和一个额外的cursor.updateRow(row)
。
结果,您的print
语句未正确缩进。尝试运行以下Update Cursor:
import arcpy
fc = '/path/to/your/geodatabase.gdb/feature_class'
# Add field
arcpy.AddField(fc,"FERRY",field_type = "TEXT")
# Update attributes based on a condition
# Note row[0] is "FEATURE" and row[1] is "FERRY"
with arcpy.da.UpdateCursor(fc,["FEATURE","FERRY"]) as cursor:
for row in cursor:
if row[0] == "ADD YOUR CONDITION HERE":
row[1] = "YES"
else:
row[1] = "NO"
cursor.updateRow(row)