def mutil_shapefiles_merge(input_folder_path, output_shpfile_abspath, delete_area_threshold=0.03):
'''本函数用于多个矢量文件的合并
第一个参数为需要合并矢量文件的文件夹路径
第二个是合并后矢量文件的完整路径'''
ptdriver = ('ESRI Shapefile')
file_end_with = '.shp'
# 若存在同名图层,则先删除再创键
if (output_shpfile_abspath):
(output_shpfile_abspath)
print('The already existed shapefile was successfully deleted.')
out_ds = (output_shpfile_abspath)
one_shp_provide_spatial = ((input_folder_path, '*.shp'))[-1]
ds = (one_shp_provide_spatial)
ds_ly = ()
ds_spatial = ds_ly.GetSpatialRef()
srs = ds_spatial
()
out_layer = out_ds.CreateLayer(output_shpfile_abspath, srs=srs, geom_type=)
filelist = (input_folder_path)
for file in filelist:
if (file_end_with):
# 查询文件起始标志
file_abspath = (input_folder_path, file)
data_source = (file_abspath)
if data_source is None:
print("This file does not exist...")
original_layer = data_source.GetLayer()
# 根据原图层字段对象创建新图层的字段
out_layer.CreateFields(original_layer.schema)
for feat in original_layer:
out_feat = (out_layer.GetLayerDefn())
out_feat.SetGeometry(().Clone())
# out_layer.CreateFeature(out_feat)
out_layer.SyncToDisk()
# 获取原图层字段个数
original_layer_fields_count = ()
# 将原图层字段值写入到新图层中
for i in range(original_layer_fields_count):
# 这里可设置判断条件,当字段名称等于某字符时间,才将这个字段值写入到新图层中,方便保存着图斑预测概率值
field_value = (i)
# print(field_value)
out_feat.SetField(i, field_value)
out_layer.CreateFeature(out_feat)
out_ds.Destroy()
# ________删除多余无用的字段
# 第一步,获取需要删除的字段
dataR = (output_shpfile_abspath, encoding='gbk')
fields =
field_list = []
for field in fields:
field_list.append(field[0])
delete_field_list = []
for field in field_list:
if ('DN_value') or ('Area'):
delete_field_list.append(field)
# 第二步,删除字段
dss_driver = ('ESRI Shapefile')
dss = dss_driver.Open(output_shpfile_abspath, 1)
lyr = ()
for delete_field in delete_field_list:
((delete_field, 0))
dss = None
# ________给合并后的shp添加面积字段,并计算面积
# 获取文件驱动
driver = ('ESRI Shapefile')
data_source = (output_shpfile_abspath, 1)
# 获取图层数据
layer = data_source.GetLayer(0)
# 字段定义
new_field_defn = ('AREA_ha', )
# 创建字段
(new_field_defn)
# ————————计算图斑面积
data_source = (output_shpfile_abspath, 1)
layer = data_source.GetLayer()
for feature in layer:
geom = ()
# 面积单位公顷
area = ()/10000
# 将面积添加到属性表中
('AREA_ha', round(area, 4))
(feature)
# data_source = None
# ________删除合并后shp文件中面积小于指定阈值的图斑
str_filter = 'AREA_ha' + " < '" + str(delete_area_threshold) + "'"
(str_filter)
for p_feature in layer:
p_feature_fid = p_feature.GetFID()
(int(p_feature_fid))
str_sql = "REPACK " + str(())
data_source.ExecuteSQL(str_sql, None, "")
layer = None
data_source = None