使用GDAL/OGR包+python将CSV转成shapefile并投影
在处理数据的时候,很多时候原始数据都是csv格式,分析的时候使用shapefile比较方便。特别是在mac系统上没有arcgis,处理大量数据的时候用qgis一个一个点很麻烦,于是写了个python脚本处理。 首先安装gdal的python安装包:
sudo easy_install GDAL
安装好之后就可以使用GDAL/OGR来进行数据处理了,脚本如下:
import osgeo.ogr as ogr import osgeo.osr as osr from osgeo import gdal import csv def poiMake(csvpath,shp,layerName): gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8","NO") gdal.SetConfigOption("SHAPE_ENCODING","") source = osr.SpatialReference() source.ImportFromEPSG(4326) target = osr.SpatialReference() target.ImportFromEPSG(3857) reader = csv.DictReader(open(csvpath,"rb"),delimiter=',',quoting=csv.QUOTE_MINIMAL) driver = ogr.GetDriverByName("ESRI Shapefile") data_source = driver.CreateDataSource(shp) layer = data_source.CreateLayer(layerName, target, ogr.wkbPoint) field_name = ogr.FieldDefn("en", ogr.OFTString) field_name.SetWidth(100) layer.CreateField(field_name) field_cn = ogr.FieldDefn("cn", ogr.OFTString) field_cn.SetWidth(100) layer.CreateField(field_cn) for row in reader: feature = ogr.Feature(layer.GetLayerDefn()) feature.SetField("en", row['en'].lstrip('"').rstrip('"')) feature.SetField("cn", row['cn'].lstrip('"').rstrip('"')) wkt = "POINT(%f %f)" % (float(row['lon']) , float(row['lat'])) transform = osr.CoordinateTransformation(source, target) point = ogr.CreateGeometryFromWkt(wkt) point.Transform(transform) feature.SetGeometry(point) layer.CreateFeature(feature) feature.Destroy() data_source.Destroy()
代码很简单,就不多解释了,其中最关键的是下面两句:
gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8","NO")
gdal.SetConfigOption("SHAPE_ENCODING","")
用来解决中文字符的问题
查看原文:http://www.giser.net/?p=1322
转载自:https://blog.csdn.net/barry114/article/details/46402867