-
Notifications
You must be signed in to change notification settings - Fork 2
/
fieldSelectShp.py
55 lines (49 loc) · 1.95 KB
/
fieldSelectShp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# -*- coding: utf-8 -*-
"""按属性分割矢量"""
from osgeo import ogr, gdal
import os, time
from multiprocessing.dummy import Pool as ThreadPool
def main(shpfile, outPath, Field):
ds = ogr.Open(shpfile)
lyr = ds.GetLayer(0)
gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")
gdal.SetConfigOption("SHAPE_ENCODING", "GBK")
driver = ogr.GetDriverByName("ESRI Shapefile")
numworkers = 16
pool = ThreadPool(numworkers) # 创建多线程
def write_features(feat):
cityName = feat.GetField(Field) # 以字段名为文件名称
outShp = os.path.join(outPath, str(cityName) + '.shp')
geom = feat.GetGeometryRef()
if not os.path.exists(outShp):
outDs = driver.CreateDataSource(outShp)
outLyr = outDs.CreateLayer("layername", lyr.GetSpatialRef(), ogr.wkbMultiPolygon)
outLyr.CreateFields(lyr.schema) # 创建字段属性
outFeat = ogr.Feature(lyr.GetLayerDefn())
for i in range(feat.GetFieldCount()):
val = feat.GetField(i)
outFeat.SetField(i, val)
outFeat.SetGeometry(geom)
outLyr.CreateFeature(outFeat)
outDs = None
else:
outDs = ogr.Open(outShp, 1)
outLyr = outDs.GetLayerByIndex(0)
outFeat = ogr.Feature(lyr.GetLayerDefn())
for i in range(feat.GetFieldCount()):
val = feat.GetField(i)
outFeat.SetField(i, val)
outFeat.SetGeometry(geom)
outLyr.CreateFeature(outFeat)
outDs = None
pool.map(write_features, lyr)
pool.close()
pool.join()
if __name__ == "__main__":
start = time.time()
shapePath = "a.shp" # shp path
outputPath = "output_path" # result path
Field = "name" # Field
main(shapePath, outputPath, Field)
end = time.time()
print("用时{}秒".format((end - start)))