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 虽然天天跟数据打交 ...
随机推荐
- LINUX SSH修改默认22/添加端口
通常ssh远程登录的默认端口是22,但是因为端口22属于高危端口,因此很多时候作为服务器会被关掉,不过这个端口一般是可以更改或者添加的,这样除了22端口,也可以通过别的端口进行访问. 1.首先修改配置 ...
- 微信小程序之 ----API接口
1. wx.request 接口 可在文件 wxs中操作,连接服务器处理数据 参数 ① url ② data ③ header ④ method ⑤ dataType 回调 ...
- Windows系统崩溃后快速恢复Oracle数据库的妙招
Windows系统崩溃后快速恢复Oracle数据库,以下是操作步骤 假设oracle数据安装在d:\\oracle文件夹中,数据库名称orcl 1>将崩溃的数据库安装目录"d:\\or ...
- System.ServiceProcess.TimeoutException: Time out has expired and the operation has not been completed.
项目代码如下 ServiceController service = new ServiceController("ModbusAgent"); service.Stop(); T ...
- vue的通讯与传递props emit (简单的弹框组件)
props父把信息传递给子组件 1父组件 <template> <div class="hello"> <div id="app-3&quo ...
- 进程同步(multiprocess.Lock、multiprocess.Semaphore、multiprocess.Event) day38
进程同步(multiprocess.Lock.multiprocess.Semaphore.multiprocess.Event) 锁 —— multiprocess.Lock 通过刚刚的学习,我们千 ...
- Java的OOP三大特征之一——封装
面向对象三大特征之一 封装 继承 多态 封装性就是把类(对象)的属性和行为结合成一个独立的相同单位,并尽可能隐蔽类(对象)的内部细节,对外形成一个边界,只保留有限的对外接口使之与外部发生联系. ...
- [最新原创电子书]lazarus开发者入门及中级教程
目前市面上没有任何一本完整的书,介绍Lazarus,Firebird这两个优秀的开发工具,同时还有一个作为他们之间桥梁的开发套件ZeosDBO,也没有任何完整的中文开发指南,本书以这三种开发套件为主线 ...
- sqli-labs:1-4,基于报错的注入
sqli1: 脚本 # -*- coding: utf-8 -*- """ Created on Sat Mar 23 09:37:14 2019 @author: ke ...
- Java关键字解释及作用
JAVA 关键字及其作用解释 1. 访问控制 1) private 私有的 private 关键字是访问控制修饰符,可以应用于类.方法或字段(在类中声明的变量). 只能在声明 private(内部)类 ...