从shp中用属性过滤要素,并保持到新数据中
# -*- coding: utf-8 -*-
# @Time : 2022/7/26 9:59
# @Author : xll
from osgeo import gdal, ogr, osr
if __name__ == '__main__':
tif_grid_file = r"E:\data\14-17切图\p8shp\p8_new.shp"
todo_file = r'E:\data\bc16\p8检查\mx5-23-12.txt'
out_file = r'E:\data\bc16\p8检查\mx5-23-12.gpkg'
tif_lst = []
with open(todo_file, 'r') as fp:
for line in fp.readlines():
line = line.strip()
tif_name = line
tif_lst.append("name='{tif_name}'".format(tif_name=tif_name))
outDriver = ogr.GetDriverByName("GPKG")
outDataSource = outDriver.CreateDataSource(out_file)
inDriver = ogr.GetDriverByName("ESRI Shapefile")
inDataSource = inDriver.Open(tif_grid_file, 0)
inLayer = inDataSource.GetLayer()
inLayer.SetAttributeFilter(' or '.join(tif_lst))
# inLayer.SetAttributeFilter("name='{tif_name}'".format(tif_name=tif_name))
print(inLayer.GetFeatureCount())
outDataSource.CopyLayer(inLayer, "p8")
inLayer.SetAttributeFilter(None)
inDataSource = None
# Save and close DataSource
outDataSource = None