使用arcpy.da.UpdateCursor

时间:2018-05-15 05:18:56

标签: arcpy

我有一个数据集中的字段列表,这些字段是字符串类型字段。 我需要从这些字段中的所有行中删除空格。

我的代码是:

import arcpy
dataset = r'Database Connections\xxxx.sde\GISUSA.PET_Wells'
fields = arcpy.ListFields(dataset)
for field in fields:
    if field.type =="String":
       list_of_fields.append(field.name)
for i in list_of_fields:
    with arcpy.da.UpdateCursor(dataset, "{}".format(i)) as cursor:
        for row in cursor:
            row[0]=row[0].strip()
            cursor.updateRow(row)

我收到错误:

  

运行时错误Traceback(最近一次调用最后一次):文件“”,   第4行,在AttributeError中:'NoneType'对象没有属性   '条带'

我在行

中猜测i的值
with arcpy.da.UpdateCursor(dataset, "{}".format(i)) as cursor:

的格式不正确。

我测试过不同的格式,'“{}”'。format(i)。放入UpdateCursor时也会出错。

此代码打印正确格式化的值,带有双重quoatation标记,这是UpdateCursor中的字段所必需的

>>> for i in list_of_fields:
...     print '"{}"'.format(i)
  

...“WELL_UWI”“WELL_NAME”“ELEV_TYPE”“CURRENT_STATUS”   “SPUD_DATE”“COMPLETION”“FIELD”“WL_COUNTY”“WL_STATE”   “DRILLING_OPERATOR”“CURRENT_WELL_LEASE_NAME”“备注”

for i in list_of_fields:
...     with arcpy.da.UpdateCursor(dataset, '"{}"'.format(i)) as cursor:
...         for row in cursor:
...             row[0]=row[0].strip()
...             cursor.updateRow(row)
  

运行时错误Traceback(最近一次调用最后一次):文件“”,   第10行,在RuntimeError中:找不到字段'“WELL_UWI”'

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

list_of_fields中的值已经是字符串,UpdateCursor接受字段列表或带有字段名称的字符串。不需要对值进行任何格式化。

只是这样做:

for i in list_of_fields:
    with arcpy.da.UpdateCursor(dataset, i) as cursor:
        for row in cursor:
            row[0]=row[0].strip()
            cursor.updateRow(row)

你也试图摆脱所有空白空间或只是在字符串的开头和结尾?如果你想摆脱所有空间,你应该使用string.replace(' ','')

答案 1 :(得分:0)

经过一些跟踪和错误后,这有效:

for i in list_of_fields:
     with arcpy.da.UpdateCursor(dataset, i) as cursor:
         for row in cursor:
            row[0]=str(row[0]).strip()
            cursor.updateRow(row)