>>> from env_helper import info; info()
页面更新时间: 2023-06-23 10:04:54
运行环境:
Linux发行版本: Debian GNU/Linux 12 (bookworm)
操作系统内核: Linux-6.1.0-9-amd64-x86_64-with-glibc2.36
Python版本: 3.11.2
4.1. 使用OGR模块打开矢量数据¶
首先来看一下使用Python如何对矢量数据进行操作。
4.1.1. 导入 ogr
模块¶
在 Python 中使用 OGR,只需要导入ogr模块。在早期的版本中,OGR是使用
import ogr
语句导入的。
目前建议的方法:
>>> from osgeo import ogr
为了保持兼容性,同样可以使用下面的方法:
>>> try:
>>> from osgeo import ogr
>>> except:
>>> import ogr
4.1.2. 读取数据¶
先看一下使用ogr读取数据的简单流程:

图 4.1 OGR读取数据流程¶
首先我们先看一下如何打开一个数据。这里使用矢量数据常用的数据集ESRI的ShapeFile。 可以使用ogr.Open()函数直接打开矢量数据,在这个过程中,ogr会自动根据文件的类型来确定相应的驱动
>>> inshp = '/gdata/GSHHS_c.shp'
>>> from osgeo import ogr
>>> datasource = ogr.Open(inshp)
>>> driver = datasource.GetDriver()
>>> driver.name
>>>
'ESRI Shapefile'
这样就打开了一个数据源(DataSource),并将其赋给datasource变量。
4.1.3. OGR的数据驱动¶
上面这种方法打开的是按缺省方式进行的,在实际编程中,应该对要打开的数据类型进行一下处理。要读取某种类型的数据,必须要先载入数据驱动,也就是初始化一个对象,让它“知道”某种数据结构。
driver = ogr.GetDriverByName(‘ESRI Shapefile’)
数据驱动driver的Open()(方法返回一个数据源对象),其中update为0是只读,为1是可写)。 例如:
Open(self, char name, int update = 0) -> DataSource
>>> import sys
>>> from osgeo import ogr
>>>
>>> driver = ogr.GetDriverByName('ESRI Shapefile')
>>> dataSource = driver.Open(inshp,0)
>>> if dataSource is None:
>>> print ('could not open')
>>> sys.exit(1)
>>> print ('done!')
done!
注意filename一定要写绝对路径! 使用Python的内省函数dir()看一下datasource有哪些可用的方法。
>>> dir(datasource)[:10]
['AbortSQL',
'CommitTransaction',
'CopyLayer',
'CreateLayer',
'DeleteLayer',
'Dereference',
'Destroy',
'ExecuteSQL',
'FlushCache',
'GetDescription']