多个矢量文件合并为一个矢量文件

本文介绍了一段Python代码,利用GDAL库将多个矢量文件合并成一个,适合根据个人需求进行调整,已解决常见问题。
摘要由CSDN通过智能技术生成

见如下代码。

这个代码是根据我自己业务需要写的,整体是可以根据自己的需要进行适当调整和修改。许多坑已经都跨过去了。

def mutil_shapefiles_merge(input_folder_path, output_shpfile_abspath, delete_area_threshold=0.03):
    '''本函数用于多个矢量文件的合并
    第一个参数为需要合并矢量文件的文件夹路径
    第二个是合并后矢量文件的完整路径'''
    ptdriver = ogr.GetDriverByName('ESRI Shapefile')
    file_end_with = '.shp'
    # 若存在同名图层,则先删除再创键
    if os.path.exists(output_shpfile_abspath):
        ptdriver.DeleteDataSource(output_shpfile_abspath)
        print('The already existed shapefile was successfully deleted.')

    out_ds = ptdriver.CreateDataSource(output_shpfile_abspath)
    one_shp_provide_spatial = glob.glob(os.path.join(input_folder_path, '*.shp'))[-1]
    ds = ogr.Open(one_shp_provide_spatial)
    ds_ly = ds.GetLayer()
    ds_spatial = ds_ly.GetSpatialRef()
    srs = ds_spatial
    ds.Destroy()
    out_layer = out_ds.CreateLayer(
合并多个矢量文件,我们可以使用Python中的GDAL(地理数据抽象库)来实现。GDAL一个功能强大的开源地理数据处理库,可以处理各种格式的矢量数据。 首先,我们需要安装GDAL库。可以通过在命令行中运行"pip install gdal"来安装。 接下来,我们可以使用以下代码来合并多个矢量文件: ``` from osgeo import ogr # 创建输出文件 output_file = "merged.shp" driver = ogr.GetDriverByName("ESRI Shapefile") output_ds = driver.CreateDataSource(output_file) output_layer = output_ds.CreateLayer("merged", geom_type=ogr.wkbPolygon) # 读取要合并矢量文件列表 input_files = ["file1.shp", "file2.shp", "file3.shp"] # 遍历每个输入文件 for input_file in input_files: input_ds = ogr.Open(input_file) input_layer = input_ds.GetLayer() # 获取输入图层中的要素 for feature in input_layer: # 创建新要素 output_feature = ogr.Feature(output_layer.GetLayerDefn()) output_feature.SetGeometry(feature.GetGeometryRef()) # 将新要素添加到输出图层 output_layer.CreateFeature(output_feature) # 关闭输入数据源 input_ds = None # 保存并关闭输出数据源 output_ds = None print("矢量文件已成功合并为", output_file) ``` 在上面的代码中,我们首先创建了一个输出数据源(Shapefile格式),然后遍历要合并的每个输入文件。对于每个输入文件,我们打开它,获取图层中的要素,并将每个要素添加到输出图层中。最后,我们保存并关闭输出数据源。 这样,我们就成功地将多个矢量文件合并一个文件"merged.shp"。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

John H.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值