使用arcpy.da.UpdateCursor处理字符串字段去空格报错求助
解决ArcPy更新字符串字段空格时的两个常见问题
我来帮你搞定这两个问题,咱们一步步拆解分析:
首先看你遇到的第一个错误:
Runtime error Traceback (most recent call last): File "", line 4, in AttributeError: 'NoneType' object has no attribute 'strip'
这个问题和字段格式完全无关,核心是你的数据里存在空值(None)!当某行的字段值是None时,直接调用.strip()自然会报错——毕竟None没有这个方法。所以第一步要做的是先判断值是否为空,再处理空格。
然后是第二个错误:
Runtime error Traceback (most recent call last): File "", line 10, in RuntimeError: Cannot find field '"WELL_UWI"'
你给字段名额外加了双引号,导致ArcGIS去查找名字带引号的字段,当然找不到啦!arcpy.da.UpdateCursor的字段参数直接传字段名字符串就行,不需要额外套引号。
另外你的代码还有个小疏漏:list_of_fields一开始没初始化,运行时会触发NameError,这个也得补上。
下面是修正后的完整代码:
import arcpy dataset = r'Database Connections\xxxx.sde\GISUSA.PET_Wells' fields = arcpy.ListFields(dataset) list_of_fields = [] # 初始化字段列表,避免未定义错误 # 收集所有String类型字段 for field in fields: if field.type == "String": list_of_fields.append(field.name) # 遍历字段,处理空值并去除首尾空格 for field_name in list_of_fields: with arcpy.da.UpdateCursor(dataset, field_name) as cursor: for row in cursor: # 先判断值不为空,再执行strip操作 if row[0] is not None: row[0] = row[0].strip() cursor.updateRow(row)
关键修改说明:
- 初始化
list_of_fields列表,解决未定义的报错 - 移除字段名的多余引号,直接传递原始字段名给UpdateCursor
- 增加
if row[0] is not None的判断,跳过空值,避免AttributeError
这样修改后,代码就能正常运行,把所有字符串字段的首尾空格清除,同时不会因为空值触发报错了。
内容的提问来源于stack exchange,提问作者lida




