使用ogr
库实现 wkt
格式的几何数据转换为 kml
格式的简单实现。
#!/usr/bin/env python import argparse import os from osgeo import ogr # 读取 wkt 文件,这里只返回了第一行 def readWktFile(filename): f = open(filename) data = f.readlines() f.close() return data[0] # 参考: https://pcjericks.github.io/py-gdalogr-cookbook/geometry.html def wkt2kml(wkt): geometry = ogr.CreateGeometryFromWkt(wkt) return geometry.ExportToKML() def wkt2geojson(wkt): geometry = ogr.CreateGeometryFromWkt(wkt) return geometry.ExportToJson() def writeFile(filename, data): fo = open(filename, "wb") fo.write(data) def main(): print("读取指定 wkt 文件列表(一行一个)") parser = argparse.ArgumentParser(description='转换 WKT 文件为 KML') parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),default=sys.stdin) args = parser.parse_args() wktFileList = args.infile.read().splitlines() wktDirectory = "wkt/" # wkt 文件所在目录 kmlDirectory = "kml/" # kml 文件输出目录 ogr.RegisterAll() for wktFile in wktFileList: print("处理 %s" % wktFile) wkt = readWktFile(wktDirectory + filename) kml = wkt2kml(wkt) # 补全kml文件信息(这里 wkt 文件后缀名都是 .wkt ) prefix = '<?xml version="1.0" encoding="utf-8" ?>\ <kml xmlns="http://www.opengis.net/kml/2.2">\ <Document id="root_doc"><Folder><name>%s</name>\ <Placemark>' % filename[0:-4] suffix = '</Placemark></Folder></Document></kml>' kml = prefix + kml + suffix writeFile(kmlDirectory + filename[0:-4] + ".kml", kml.encode()) if __name__ == "__main__": main()