GDAL读写矢量文件——Python

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

图1 Python创建矢量结果

1 #-*- coding: cp936 -*-
2 try:
3          from osgeo import gdal
4          from osgeo import ogr
5 exceptImportError:
6          import gdal
7          import ogr

1.读取矢量

 1 #-*- coding: cp936 -*-
 2 try:
 3          from osgeo import gdal
 4          from osgeo import ogr
 5 exceptImportError:
 6          import gdal
 7          import ogr
 8
 9 defReadVectorFile():
10          # 为了支持中文路径,请添加下面这句代码
11          gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8","NO")
12          # 为了使属性表字段支持中文,请添加下面这句
13          gdal.SetConfigOption("SHAPE_ENCODING","")
14
15          strVectorFile ="E:\\Datum\\GDALCsTest\\Debug\\beijing.shp"
16
17          # 注册所有的驱动
18          ogr.RegisterAll()
19
20          #打开数据
21          ds = ogr.Open(strVectorFile, 0)
22          if ds == None:
23                    print("打开文件【%s】失败!", strVectorFile)
24                    return
25
26          print("打开文件【%s】成功!", strVectorFile)
27
28          # 获取该数据源中的图层个数,一般shp数据图层只有一个,如果是mdb、dxf等图层就会有多个
29          iLayerCount = ds.GetLayerCount()
30
31          # 获取第一个图层
32          oLayer = ds.GetLayerByIndex(0)
33          if oLayer == None:
34                    print("获取第%d个图层失败!\n", 0)
35                    return
36
37          # 对图层进行初始化,如果对图层进行了过滤操作,执行这句后,之前的过滤全部清空
38          oLayer.ResetReading()
39
40          # 通过属性表的SQL语句对图层中的要素进行筛选,这部分详细参考SQL查询章节内容
41          oLayer.SetAttributeFilter("\"NAME99\"LIKE \"北京市市辖区\"")
42
43          # 通过指定的几何对象对图层中的要素进行筛选
44          #oLayer.SetSpatialFilter()
45
46          # 通过指定的四至范围对图层中的要素进行筛选
47          #oLayer.SetSpatialFilterRect()
48
49          # 获取图层中的属性表表头并输出
50          print("属性表结构信息:")
51          oDefn = oLayer.GetLayerDefn()
52          iFieldCount = oDefn.GetFieldCount()
53          for iAttr in range(iFieldCount):
54                    oField =oDefn.GetFieldDefn(iAttr)
55                    print( "%s: %s(%d.%d)" % ( 56                                      oField.GetNameRef(),57                                      oField.GetFieldTypeName(oField.GetType() ), 58                                      oField.GetWidth(),59                                      oField.GetPrecision()))
60
61          # 输出图层中的要素个数
62          print("要素个数 = %d", oLayer.GetFeatureCount(0))
63
64          oFeature = oLayer.GetNextFeature()
65          # 下面开始遍历图层中的要素
66          while oFeature is not None:
67                    print("当前处理第%d个: \n属性值:", oFeature.GetFID())
68                    # 获取要素中的属性表内容
69                    for iField inrange(iFieldCount):
70                             oFieldDefn =oDefn.GetFieldDefn(iField)
71                             line =  " %s (%s) = " % ( 72                                                oFieldDefn.GetNameRef(),73                                                ogr.GetFieldTypeName(oFieldDefn.GetType()))
74
75                             ifoFeature.IsFieldSet( iField ):
76                                      line = line+ "%s" % (oFeature.GetFieldAsString( iField ) )
77                             else:
78                                      line = line+ "(null)"
79
80                             print(line)
81
82                    # 获取要素中的几何体
83                    oGeometry =oFeature.GetGeometryRef()
84
85                    # 为了演示,只输出一个要素信息
86                    break
87
88          print("数据集关闭!")

执行上面的代码,如果不设置属性过滤,输出内容如图3?9上半部分所示,如过设置了属性过滤,输出内容如图3?9下半部分所示。(Python输出的中文转为编码了)。

图2 OGR库使用Python读取矢量示例

2.写入矢量

在使用Python创建矢量图形的时候,使用的WKT格式的字符串来进行创建。也可以使用其他的方式进行创建。代码如下,写出来的矢量图形和属性表如图1所示。

 1 #-*- coding: cp936 -*-
 2 try:
 3          from osgeo import gdal
 4          from osgeo import ogr
 5 exceptImportError:
 6          import gdal
 7          import ogr
 8
 9 defWriteVectorFile():
10          # 为了支持中文路径,请添加下面这句代码
11          gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8","NO")
12          # 为了使属性表字段支持中文,请添加下面这句
13          gdal.SetConfigOption("SHAPE_ENCODING","")
14
15          strVectorFile ="E:\\TestPolygon.shp"
16
17          # 注册所有的驱动
18          ogr.RegisterAll()
19
20          # 创建数据,这里以创建ESRI的shp文件为例
21          strDriverName = "ESRIShapefile"
22          oDriver =ogr.GetDriverByName(strDriverName)
23          if oDriver == None:
24                    print("%s 驱动不可用!\n", strDriverName)
25                    return
26
27          # 创建数据源
28          oDS =oDriver.CreateDataSource(strVectorFile)
29          if oDS == None:
30                    print("创建文件【%s】失败!", strVectorFile)
31                    return
32
33          # 创建图层,创建一个多边形图层,这里没有指定空间参考,如果需要的话,需要在这里进行指定
34          papszLCO = []
35          oLayer =oDS.CreateLayer("TestPolygon", None, ogr.wkbPolygon, papszLCO)
36          if oLayer == None:
37                    print("图层创建失败!\n")
38                    return
39
40          # 下面创建属性表
41          # 先创建一个叫FieldID的整型属性
42          oFieldID =ogr.FieldDefn("FieldID", ogr.OFTInteger)
43          oLayer.CreateField(oFieldID, 1)
44
45          # 再创建一个叫FeatureName的字符型属性,字符长度为50
46          oFieldName =ogr.FieldDefn("FieldName", ogr.OFTString)
47          oFieldName.SetWidth(100)
48          oLayer.CreateField(oFieldName, 1)
49
50          oDefn = oLayer.GetLayerDefn()
51
52          # 创建三角形要素
53          oFeatureTriangle = ogr.Feature(oDefn)
54          oFeatureTriangle.SetField(0, 0)
55          oFeatureTriangle.SetField(1, "三角形")
56          geomTriangle =ogr.CreateGeometryFromWkt("POLYGON ((0 0,20 0,10 15,0 0))")
57          oFeatureTriangle.SetGeometry(geomTriangle)
58          oLayer.CreateFeature(oFeatureTriangle)
59
60          # 创建矩形要素
61          oFeatureRectangle = ogr.Feature(oDefn)
62          oFeatureRectangle.SetField(0, 1)
63          oFeatureRectangle.SetField(1, "矩形")
64          geomRectangle =ogr.CreateGeometryFromWkt("POLYGON ((30 0,60 0,60 30,30 30,30 0))")
65          oFeatureRectangle.SetGeometry(geomRectangle)
66          oLayer.CreateFeature(oFeatureRectangle)
67
68          # 创建五角形要素
69          oFeaturePentagon = ogr.Feature(oDefn)
70          oFeaturePentagon.SetField(0, 2)
71          oFeaturePentagon.SetField(1, "五角形")
72          geomPentagon =ogr.CreateGeometryFromWkt("POLYGON ((70 0,85 0,90 15,80 30,65 15,700))")
73          oFeaturePentagon.SetGeometry(geomPentagon)
74          oLayer.CreateFeature(oFeaturePentagon)
75
76          oDS.Destroy()
77          print("数据集创建完成!\n")

3.矢量数据管理

 1 defVectorDelete(strVectorFile):
 2          # 注册所有的驱动
 3          ogr.RegisterAll()
 4
 5          oDriver = None
 6          #打开矢量
 7          oDS = ogr.Open(strVectorFile, 0)
 8          if oDS == None:
 9                    os.remove(strVectorFile)
10                    return
11
12          oDriver = oDS.GetDriver()
13          if oDriver == None:
14                    os.remove(strVectorFile)
15                    return
16
17          ifoDriver.DeleteDataSource(strVectorFile) == ogr.OGRERR_NONE:
18                    return
19          else:
20                    os.remove(strVectorFile)
21
22 defVectorRename(strOldFile, strNewFile):
23          # 注册所有的驱动
24          ogr.RegisterAll()
25
26          oDriver = None
27          #打开矢量
28          oDS = Ogr.Open(strOldFile, 0)
29          if oDS == None :
30                    os.rename(strOldFile,strNewFile)
31                    return
32
33          oDriver = oDS.GetDriver()
34          if oDriver == None:
35                    os.rename(strOldFile,strNewFile)
36                    return
37
38          oDDS = oDriver.CopyDataSource(oDS,strNewFile, None)
39          if oDDS == None:
40                    os.rename(strOldFile,strNewFile)
41
42          if oDriver.DeleteDataSource(strOldFile)== ogr.OGRERR_NONE:
43                    return
44          else :
45                    os.rename(strOldFile,strNewFile)

文章来源:http://blog.csdn.net/liminlu0314/article/details/8828983

时间: 2025-01-16 05:59:08

GDAL读写矢量文件——Python的相关文章

python读写操作文件

with open(xxx,'r,coding='utf-8') as f:   #打开文件赋值给F ,并且执行完了之后不需要 f.close(). 在Python 2.7 及以后,with又支持同时对多个文件的上下文进行管理,即:with open('log1') as obj1, open('log2') as obj2: f.tell          #获取指针位置 f.seek(1)   #调整指针位置 f.writ()     #往文件里面些东西  并切指针到最后 r.read() 

【python下使用OpenCV实现计算机视觉读书笔记3】读写视频文件

Lua可以调用C函数的能力将极大的提高Lua的可扩展性和可用性. 对于有些和操作系统相关的功能,或者是对效率要求较高的模块,我们完全可以通过C函数来实现,之后再通过Lua调用指定的C函数. 对于那些可被Lua调用的C函数而言,其接口必须遵循Lua要求的形式,即typedef int (*lua_CFunction)(lua_State* L). 简单说明一下,该函数类型仅仅包含一个表示Lua环境的指针作为其唯一的参数,实现者可以通过该指针进一步获取Lua代码中实际传入的参数.返回值是整型,表示该

[转]用Python读写Excel文件

转自:http://www.gocalf.com/blog/python-read-write-excel.html#xlrd-xlwt 虽然天天跟数据打交道,也频繁地使用Excel进行一些简单的数据处理和展示,但长期以来总是小心地避免用Python直接读写Excel文件.通常我都是把数据保存为以TAB分割的文本文件(TSV),再在Excel中进行导入或者直接复制粘贴. 前段时间做一个项目,却不得不使用Python直接生成Excel文件,后来随着需求的变化,还要对已有的Excel文件进行读取.在

用Python读写Excel文件 Contents

用Python读写Excel文件 四种python处理excel模块PK 我主要尝试了四种工具,在此并不会给出他们的排名,因为在不同的应用场景下,做出的选择会不同.   XlsxWriter xlrd&xlwt OpenPyXL Microsoft Excel API 介绍 可以创建Excel 2007或更高版本的XLSX文件 即python-excel,含xlrd.xlwt和xlutils三大模块,分别提供读.写和其他功能 可以读写Excel 2007 XLSX和XLSM文件 直接通过COM组

python读写dbf文件

Python读写dbf文件 # coding=utf8 """ A reader and writer for dbf file.see http://code.activestate.com/recipes/362715/ for moe detail """ import struct import datetime import decimal import itertools def dbfreader(f):     "&qu

【python-ini】python读写ini文件

本文实例讲述了Python读写ini文件的方法.分享给大家供大家参考.具体如下: 比如有一个文件update.ini,里面有这些内容: 1 2 3 4 5 6 7 8 [ZIP] EngineVersion=0 DATVersion=5127 FileName=dat-5127.zip FilePath=/pub/antivirus/datfiles/4.x/ FileSize=13481555 Checksum=6037,021E MD5=aaeb519d3f276b810d46642d782

python 读写json文件(dump, load),以及对json格式的数据处理(dumps, loads)

JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式.它基于ECMAScript的一个子集. 1.json.dumps()和json.loads()是json格式处理函数(可以这么理解,json是字符串) json.dumps()函数是将一个Python数据类型列表进行json格式的编码(可以这么理解,json.dumps()函数是将字典转化为字符串) json.loads()函数是将json格式数据转换为字典(可以这么理解,json.loads()函数

用Python读写Excel文件的方式比较

虽然天天跟数据打交道,也频繁地使用Excel进行一些简单的数据处理和展示,但长期以来总是小心地避免用Python直接读写Excel文件.通常我都是把数据保存为以TAB分割的文本文件(TSV),再在Excel中进行导入或者直接复制粘贴. 前段时间做一个项目,却不得不使用Python直接生成Excel文件,后来随着需求的变化,还要对已有的Excel文件进行读取.在这个过程中,研究并尝试了一些工具,也走了一些弯路.记录下来,下次再有类似需求的时候就不用漫天遍野地搜索了. 超级无敌大PK 我主要尝试了四

python操作txt文件中数据教程[1]-使用python读写txt文件

python操作txt文件中数据教程[1]-使用python读写txt文件 觉得有用的话,欢迎一起讨论相互学习~Follow Me 原始txt文件 程序实现后结果 程序实现 filename = './test/test.txt' contents = [] DNA_sequence = [] # 打开文本并将所有内容存入contents中 with open(filename, 'r') as f: for line in f.readlines(): contents.append(line