用phython写出kml批量转换shp
时间: 2023-05-11 22:06:55 浏览: 583
可以使用 pyKML 库来实现批量转换 kml 到 shp,以下是示例代码:
```python
from os import listdir
from os.path import isfile, join
from pykml import parser
from osgeo import ogr
# 输入 kml 文件夹路径和输出 shp 文件夹路径
kml_folder = 'path/to/kml/folder'
shp_folder = 'path/to/shp/folder'
# 获取 kml 文件列表
kml_files = [f for f in listdir(kml_folder) if isfile(join(kml_folder, f)) and f.endswith('.kml')]
# 遍历 kml 文件列表
for kml_file in kml_files:
# 解析 kml 文件
with open(join(kml_folder, kml_file), 'rb') as f:
root = parser.parse(f).getroot()
# 获取 kml 文件中的坐标点
coordinates = []
for placemark in root.Document.Folder.Placemark:
for point in placemark.MultiGeometry.Point:
coordinates.append([float(c) for c in point.coordinates.text.split(',')])
# 创建 shp 文件
shp_file = join(shp_folder, kml_file.replace('.kml', '.shp'))
driver = ogr.GetDriverByName('ESRI Shapefile')
ds = driver.CreateDataSource(shp_file)
layer = ds.CreateLayer('', None, ogr.wkbPoint)
layer_defn = layer.GetLayerDefn()
# 添加坐标点到 shp 文件
for coordinate in coordinates:
feature = ogr.Feature(layer_defn)
point = ogr.Geometry(ogr.wkbPoint)
point.AddPoint(coordinate[0], coordinate[1])
feature.SetGeometry(point)
layer.CreateFeature(feature)
# 释放资源
ds = None
```
这段代码会遍历指定的 kml 文件夹,将每个 kml 文件中的坐标点提取出来,并创建对应的 shp 文件。
阅读全文