GDAL读写矢量文件——Python
在Python中使用OGR时,先要导入OGR库,如果需要对中文的支持,还需要导入GDAL库,具体代码如下。Python创建的shp结果如图1所示。

图1 Python创建矢量结果
#-*- coding: cp936 -*-
try:
from osgeo import gdal
from osgeo import ogr
exceptImportError:
import gdal
import ogr
1.读取矢量
#-*- coding: cp936 -*-
try:
from osgeo import gdal
from osgeo import ogr
exceptImportError:
import gdal
import ogr defReadVectorFile():
# 为了支持中文路径,请添加下面这句代码
gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8","NO")
# 为了使属性表字段支持中文,请添加下面这句
gdal.SetConfigOption("SHAPE_ENCODING","") strVectorFile ="E:\\Datum\\GDALCsTest\\Debug\\beijing.shp" # 注册所有的驱动
ogr.RegisterAll() #打开数据
ds = ogr.Open(strVectorFile, 0)
if ds == None:
print("打开文件【%s】失败!", strVectorFile)
return print("打开文件【%s】成功!", strVectorFile) # 获取该数据源中的图层个数,一般shp数据图层只有一个,如果是mdb、dxf等图层就会有多个
iLayerCount = ds.GetLayerCount() # 获取第一个图层
oLayer = ds.GetLayerByIndex(0)
if oLayer == None:
print("获取第%d个图层失败!\n", 0)
return # 对图层进行初始化,如果对图层进行了过滤操作,执行这句后,之前的过滤全部清空
oLayer.ResetReading() # 通过属性表的SQL语句对图层中的要素进行筛选,这部分详细参考SQL查询章节内容
oLayer.SetAttributeFilter("\"NAME99\"LIKE \"北京市市辖区\"") # 通过指定的几何对象对图层中的要素进行筛选
#oLayer.SetSpatialFilter() # 通过指定的四至范围对图层中的要素进行筛选
#oLayer.SetSpatialFilterRect() # 获取图层中的属性表表头并输出
print("属性表结构信息:")
oDefn = oLayer.GetLayerDefn()
iFieldCount = oDefn.GetFieldCount()
for iAttr in range(iFieldCount):
oField =oDefn.GetFieldDefn(iAttr)
print( "%s: %s(%d.%d)" % ( \
oField.GetNameRef(),\
oField.GetFieldTypeName(oField.GetType() ), \
oField.GetWidth(),\
oField.GetPrecision())) # 输出图层中的要素个数
print("要素个数 = %d", oLayer.GetFeatureCount(0)) oFeature = oLayer.GetNextFeature()
# 下面开始遍历图层中的要素
while oFeature is not None:
print("当前处理第%d个: \n属性值:", oFeature.GetFID())
# 获取要素中的属性表内容
for iField inrange(iFieldCount):
oFieldDefn =oDefn.GetFieldDefn(iField)
line = " %s (%s) = " % ( \
oFieldDefn.GetNameRef(),\
ogr.GetFieldTypeName(oFieldDefn.GetType())) ifoFeature.IsFieldSet( iField ):
line = line+ "%s" % (oFeature.GetFieldAsString( iField ) )
else:
line = line+ "(null)" print(line) # 获取要素中的几何体
oGeometry =oFeature.GetGeometryRef() # 为了演示,只输出一个要素信息
break print("数据集关闭!")
执行上面的代码,如果不设置属性过滤,输出内容如图3‑9上半部分所示,如过设置了属性过滤,输出内容如图3‑9下半部分所示。(Python输出的中文转为编码了)。

图2 OGR库使用Python读取矢量示例
2.写入矢量
在使用Python创建矢量图形的时候,使用的WKT格式的字符串来进行创建。也可以使用其他的方式进行创建。代码如下,写出来的矢量图形和属性表如图1所示。
#-*- coding: cp936 -*-
try:
from osgeo import gdal
from osgeo import ogr
exceptImportError:
import gdal
import ogr defWriteVectorFile():
# 为了支持中文路径,请添加下面这句代码
gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8","NO")
# 为了使属性表字段支持中文,请添加下面这句
gdal.SetConfigOption("SHAPE_ENCODING","") strVectorFile ="E:\\TestPolygon.shp" # 注册所有的驱动
ogr.RegisterAll() # 创建数据,这里以创建ESRI的shp文件为例
strDriverName = "ESRIShapefile"
oDriver =ogr.GetDriverByName(strDriverName)
if oDriver == None:
print("%s 驱动不可用!\n", strDriverName)
return # 创建数据源
oDS =oDriver.CreateDataSource(strVectorFile)
if oDS == None:
print("创建文件【%s】失败!", strVectorFile)
return # 创建图层,创建一个多边形图层,这里没有指定空间参考,如果需要的话,需要在这里进行指定
papszLCO = []
oLayer =oDS.CreateLayer("TestPolygon", None, ogr.wkbPolygon, papszLCO)
if oLayer == None:
print("图层创建失败!\n")
return # 下面创建属性表
# 先创建一个叫FieldID的整型属性
oFieldID =ogr.FieldDefn("FieldID", ogr.OFTInteger)
oLayer.CreateField(oFieldID, 1) # 再创建一个叫FeatureName的字符型属性,字符长度为50
oFieldName =ogr.FieldDefn("FieldName", ogr.OFTString)
oFieldName.SetWidth(100)
oLayer.CreateField(oFieldName, 1) oDefn = oLayer.GetLayerDefn() # 创建三角形要素
oFeatureTriangle = ogr.Feature(oDefn)
oFeatureTriangle.SetField(0, 0)
oFeatureTriangle.SetField(1, "三角形")
geomTriangle =ogr.CreateGeometryFromWkt("POLYGON ((0 0,20 0,10 15,0 0))")
oFeatureTriangle.SetGeometry(geomTriangle)
oLayer.CreateFeature(oFeatureTriangle) # 创建矩形要素
oFeatureRectangle = ogr.Feature(oDefn)
oFeatureRectangle.SetField(0, 1)
oFeatureRectangle.SetField(1, "矩形")
geomRectangle =ogr.CreateGeometryFromWkt("POLYGON ((30 0,60 0,60 30,30 30,30 0))")
oFeatureRectangle.SetGeometry(geomRectangle)
oLayer.CreateFeature(oFeatureRectangle) # 创建五角形要素
oFeaturePentagon = ogr.Feature(oDefn)
oFeaturePentagon.SetField(0, 2)
oFeaturePentagon.SetField(1, "五角形")
geomPentagon =ogr.CreateGeometryFromWkt("POLYGON ((70 0,85 0,90 15,80 30,65 15,700))")
oFeaturePentagon.SetGeometry(geomPentagon)
oLayer.CreateFeature(oFeaturePentagon) oDS.Destroy()
print("数据集创建完成!\n")
3.矢量数据管理
defVectorDelete(strVectorFile):
# 注册所有的驱动
ogr.RegisterAll() oDriver = None
#打开矢量
oDS = ogr.Open(strVectorFile, 0)
if oDS == None:
os.remove(strVectorFile)
return oDriver = oDS.GetDriver()
if oDriver == None:
os.remove(strVectorFile)
return ifoDriver.DeleteDataSource(strVectorFile) == ogr.OGRERR_NONE:
return
else:
os.remove(strVectorFile) defVectorRename(strOldFile, strNewFile):
# 注册所有的驱动
ogr.RegisterAll() oDriver = None
#打开矢量
oDS = Ogr.Open(strOldFile, 0)
if oDS == None :
os.rename(strOldFile,strNewFile)
return oDriver = oDS.GetDriver()
if oDriver == None:
os.rename(strOldFile,strNewFile)
return oDDS = oDriver.CopyDataSource(oDS,strNewFile, None)
if oDDS == None:
os.rename(strOldFile,strNewFile) if oDriver.DeleteDataSource(strOldFile)== ogr.OGRERR_NONE:
return
else :
os.rename(strOldFile,strNewFile)
文章来源:http://blog.csdn.net/liminlu0314/article/details/8828983
GDAL读写矢量文件——Python的更多相关文章
- 使用GDAL/OGR读写矢量文件
感觉GIS中矢量相关内容还是挺庞杂的,并且由于版本迭代的关系,使用GDAL/OGR读写矢量的资料也有点不太一样.这里总结了一个读写矢量的示例,实现代码如下: #include <iostream ...
- python GDAL 读写shp文件
gdal包用于处理栅格数据,ogr用于处理矢量数据. 1 #!C:\Program Files\pythonxy\python\python.exe 2 #-*- coding:gb2312 -*- ...
- Python使用读写excel文件
Python使用openpyxl读写excel文件 这是一个第三方库,可以处理xlsx格式的Excel文件.pip install openpyxl安装.如果使用Aanconda,应该自带了. 读取E ...
- 【转发】Python使用openpyxl读写excel文件
Python使用openpyxl读写excel文件 这是一个第三方库,可以处理xlsx格式的Excel文件.pip install openpyxl安装.如果使用Aanconda,应该自带了. 读取E ...
- (Python基础教程之十二)Python读写CSV文件
Python基础教程 在SublimeEditor中配置Python环境 Python代码中添加注释 Python中的变量的使用 Python中的数据类型 Python中的关键字 Python字符串操 ...
- C#、C++用GDAL读shp文件(转载)
C#.C++用GDAL读shp文件 C#用GDAL读shp文件 (2012-08-14 17:09:45) 标签: 杂谈 分类: c#方面的总结 1.目前使用开发环境为VS2008+GDAL1.81 ...
- 用Python读写Excel文件(转)
原文:google.com/ncr 虽然天天跟数据打交道,也频繁地使用Excel进行一些简单的数据处理和展示,但长期以来总是小心地避免用Python直接读写Excel文件.通常我都是把数据保存为以TA ...
- python读写操作文件
with open(xxx,'r,coding='utf-8') as f: #打开文件赋值给F ,并且执行完了之后不需要 f.close(). 在Python 2.7 及以后,with又支持同时 ...
- [转]用Python读写Excel文件
[转]用Python读写Excel文件 转自:http://www.gocalf.com/blog/python-read-write-excel.html#xlrd-xlwt 虽然天天跟数据打交 ...
随机推荐
- ThreadLocal ——android消息机制handler在非主线程创建not called Looper.prepare() 错误的原因
引用自:https://www.jianshu.com/p/a8fa72e708d3 引出: 使用Handler的时候,其必须要跟一个Looper绑定.在UI线程可直接初始化Handler来使用.但是 ...
- 弹出PopupWindow背景变暗的实现
弹出PopuoWindow后 代码里设置的是PopupWindow默认获取焦点 所以PopupWindow显示的时候其它控件点击是没有反应的 用到的方法是 pwMyPopWindow.setFocus ...
- Winrar发现损坏的压缩文件头
解决方法: 点击"解压到"-->保留损坏文件
- threejs指定对象旋转中心
指定对象旋转中心 默认情况下,对象的旋转中心都是自身的中心.对于组对象而言,也是如此.因此,可以利用这个特点,实现对象绕任何点旋转,也就是指定旋转中心.比如我们想要下图的对象绕A点旋转 我们可以添加 ...
- 10.18JS日记
1.JS的本质就是处理数据,数据来自后台的数据库,所以变量起到了临时存储的作用, ES制定了js的数据类型 2.数据类型有哪些? (1)字符串 String (2)数字 Number (3)布尔 B ...
- 基于Confluent.Kafka实现的KafkaConsumer消费者类和KafkaProducer消息生产者类型
一.引言 研究Kafka有一段时间了,略有心得,基于此自己就写了一个Kafka的消费者的类和Kafka消息生产者的类,进行了单元测试和生产环境的测试,还是挺可靠的. 二.源码 话不多说,直接上代码,代 ...
- Android开发之炫酷MD风格
文章转自:一点点征服的 http://www.cnblogs.com/ldq2016/p/5217590.html 安卓开发中非常炫的效果集合 这几天开发的时候,想做一些好看而且酷炫的特效,于是又开始 ...
- Hadoop(三) HADOOP常用命令参数介绍
-help 功能:输出这个命令参数手册 -ls 功能:显示目录信息 示例: hadoop fs -ls hdfs://hadoop-server01:9000/ 备注 ...
- python消息队列Queue
实例1:消息队列Queue,不要将文件命名为"queue.py",否则会报异常"ImportError: cannot import name 'Queue'" ...
- svn conflict问题解决办法
转自:http://www.cnblogs.com/aaronLinux/p/5521844.html 目录: 1. 同一处修改文件冲突 1.1. 解决方式一 1.2. 解决方式二 1.3. 解决总结 ...