不废话了,直接上封装好的函数
# -*- coding: utf-8 -*-
import os
from osgeo import ogr, osr, gdal
gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")
gdal.SetConfigOption("SHAPE_ENCODING", "UTF8")
#gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO")
#gdal.SetConfigOption( "SHAPE_ENCODING", "GBK")
def Add_Field(input_lyr, field_name, ogr_field_type):
"""
Add a field to a layer using the following ogr field types:
0 = ogr.OFTInteger
1 = ogr.OFTIntegerList
2 = ogr.OFTReal
3 = ogr.OFTRealList
4 = ogr.OFTString
5 = ogr.OFTStringList
6 = ogr.OFTWideString
7 = ogr.OFTWideStringList
8 = ogr.OFTBinary
9 = ogr.OFTDate
10 = ogr.OFTTime
11 = ogr.OFTDateTime
"""
# List fields
fields_ls = List_Fields(input_lyr)
# Check if field exist
if field_name in fields_ls:
raise Exception('Field: "{0}" already exists'.format(field_name))
# Create field
inp_field = ogr.FieldDefn(field_name, ogr_field_type)
input_lyr.CreateField(inp_field)
return inp_field
def SelectByAttribute(InShp, Field, FieldType, attriNames, coor, outShp):
ds = ogr.Open(InShp,0)
if ds is None:
raise OSError('Could not open {}'.format(InShp))
ly_count = ds.GetLayerCount()
layer = ds.GetLayer(0)
lyInfo = layer.GetLayerDefn()
driver = ogr.GetDriverByName("ESRI Shapefile")
if os.access(outShp, os.F_OK ): #如文件已存在,则删除
driver.DeleteDataSource(outShp)
ds_new = driver.CreateDataSource(outShp) #创建shp文件
spatialref_new = osr.SpatialReference()
CoorDict = {'WGS84':4326, 'BeiJing54': 4214, 'XIAN80':4610, 'CGCS2000': 4490}
spatialref_new.ImportFromEPSG(CoorDict[coor])
geomtype = ogr.wkbPolygon
layer_new = ds_new.CreateLayer(outShp[:-4], srs=spatialref_new, geom_type=geomtype,) #创建图层 for fd in fieldlist: #将字段列表写入图层
layer_new.CreateField(ogr.FieldDefn(Field, FieldType))
features = []
for i in range(layer.GetFeatureCount()):
feature = layer.GetFeature(i)
geom_polygon = feature.GetGeometryRef()
name = feature.GetField(Field)
feat = ogr.Feature(layer_new.GetLayerDefn())
if name in attriNames:
feat.SetGeometry(geom_polygon)
feat.SetField(Field, name)
features.append(feat)
for f in features:
layer_new.CreateFeature(f)
ds.Destroy()
ds_new.Destroy()
if __name__ == "__main__":
shp = 'D:/csdn/seg_new_v2/data/20220315/test.shp'
filename_new = "D:/csdn/seg_new_v2/data/20220315/temp.shp"
SelectByAttribute(shp, 'ff', ogr.OFTString, ['att'], 'CGCS2000', filename_new)
说明:
# gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")
# gdal.SetConfigOption("SHAPE_ENCODING", "UTF8")
gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO")
gdal.SetConfigOption( "SHAPE_ENCODING", "GBK")
这里下面两句是为了尝试处理字段写入属性值时中文乱码的问题,但是没有用,解决人麻烦在评论区留言。
参数说明:
SelectByAttribute(shp, 'ff', ogr.OFTString, ['att'], 'CGCS2000', filename_new)
1. shp 就是需要被选择属性的矢量文件
2. 'ff' 在这个字段里选择具有 ['att']属性的矢量
3. gr.OFTString 就是你字段的类型,后面在新的图层里创建字段的时候也要参考,类型的种类在Add_Field有给出来,不确定的话对照一下
4. ['att'] 属性列表,就是你要选择哪些属性的矢量出来,这里可以给多个
5. 'CGCS2000' 矢量对应的坐标系,代码里给了对应的编码号
6. filename_new 输出矢量,会自动创建