(二十四)arcpy开发&修改arcgis中的字段长度
首先在测试这段代码之前,我们这里新建一个字段用于测试。
然后将FID的值相等过来。
最后我们的属性表如下图所示。
那么我们来看一下代码的实现过程,首先我们读取了一个要素类,然后设置我们需要修改长度的对应字段,然后设置对应的长度。在没有将字段值删除之前,我们需要将原有的数据给保存起来。然后再将我们的shapefile数据需要删除的字段给删除点,之后就是重新创建字段了。创建完字段后,接着将原来保存好的值添加进入。至此整个过程就完了。下面我们来一下实现的代码,主要利用了UpdateCursor、SearchCursor。
import arcpy
inputtable = 'D:/Data/中国国界和省界的SHP格式数据/省界/bou2_4p.shp'
target_field='CHKJ'
fld_length=15
inputDesc = arcpy.Describe(inputtable)
print "Feature Type: " + inputDesc.featureType
print "Shape Type : " + inputDesc.shapeType
print "Shape Type : " + inputDesc.dataType
if inputDesc.dataType in ("FeatureClass", "Table","ShapeFile"):
replace_fields = ['OID@', target_field]
valueDict = {r[0]: r[1] for r in arcpy.da.SearchCursor(inputtable, replace_fields)}
with arcpy.da.UpdateCursor(inputtable, replace_fields) as cursor:
arcpy.AddMessage("delete {} field".format(target_field))
arcpy.DeleteField_management(inputtable, target_field)
arcpy.AddMessage("add {} field".format(target_field))
arcpy.AddField_management(inputtable, target_field, field_type='TEXT', field_length=int(fld_length))
arcpy.AddMessage("update field value")
for row in cursor:
row[1] = valueDict[row[0]]
cursor.updateRow(row)
arcpy.AddMessage("Finished")
else:
arcpy.AddMessage("****** Input is not Feature Class or Table ******")
最后我们来看一下实现效果。
更多内容,请微信扫二维码关注公众号,或者加入arcpy开发qq学习群:487352121
转载自:https://blog.csdn.net/u010608964/article/details/88367931