GDAl 查询并删除要素及其属性(python)

case:选择出矢量图层中符合给定条件的要素,并将其删除。这其中涉及到要素的空间查询和要素的删除等知识点。接下来将分为打开矢量数据、查询空间要素和删除空间要素三个部分做实例。

注意:矢量数据需以可读写的模式打开,即driver.Open(strFilePath,1)。此外删除要素后需要利用REPARK命令实现图形和属性删除的同步。

第一步:打开矢量数据

#注册所有驱动
gdal.AllRegister()
#解决中文路径乱码问题
gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO")
driver = ogr.GetDriverByName('ESRI Shapefile')
pFeatureDataset = driver.Open(r'D:/temp/_100.shp',1);
pFeaturelayer = pFeatureDataset.GetLayer(0)

第二部:按条件查询空间要素,本例查询字段名为Value,字段值为0的所有要素。

strValue = 0
strFilter = "Value = '" + str(strValue) + "'"
pFeaturelayer.SetAttributeFilter(strFilter)

第三部:删除第二部查询到的矢量要素,注意,此时获取到的Feature皆为选择的Feature.

 pFeatureDef = pFeaturelayer.GetLayerDefn()
 pLayerName = pFeaturelayer.GetName()
 pFieldName = "Value"
 pFieldIndex = pFeatureDef.GetFieldIndex(pFieldName)
 for pFeature in pFeaturelayer:
    pFeatureFID = pFeature.GetFID()
    pFeaturelayer.DeleteFeature(int(pFeatureFID))
  strSQL = "REPACK " + str(pFeaturelayer.GetName())
  pFeatureDataset.ExecuteSQL(strSQL, None, "");
  pFeatureLayer = None
  pFeatureDataset = None

特别需要注意的是:在写strSQL时,REPACK 命令与图层名称之间有英文状态下的空格。

转载自:https://blog.csdn.net/feixiegis/article/details/80408266

You may also like...