>>> from env_helper import info; info()
页面更新时间: 2023-12-24 17:04:57
运行环境:
    Linux发行版本: Debian GNU/Linux 12 (bookworm)
    操作系统内核: Linux-6.1.0-15-amd64-x86_64-with-glibc2.36
    Python版本: 3.11.2

5.1. 读取矢量数据

读取GIS矢量文件时,可用 Fiona的 open 函数,再用 'r' 参数打开。返回类型为 fiona.collection.Collection

>>> import fiona
>>> c = fiona.open('/gdata/prov_capital.shp', 'r')
>>> c.closed
False

其中 'r' 为缺省参数。

Fiona的 Collection 类似于Python的 file,但它返回的是迭代器,而不是文本行。

FionaDeprecationWarning: Collection.__next__() is buggy and will be removed in Fiona 2.0.

>>> next(iter(c))
<fiona.model.Feature at 0x7fc00f4c6e10>
>>> len(list(c))
34

注:list 接口覆盖的是整个 collection,就像操作 Python文件对象一样,可有效地清除它。对于遍历过的 collection 对象,不支持查找前面的文件,你必须重新打开集合,才可以返回初始部分。

>>> c = fiona.open('/gdata/prov_capital.shp')
>>> len(list(c))
34

注解:文件编码

格式驱动会尝试去检测数据的编码,但有可能会失败。 例如GDAL 1.7.2就检测不到地球自然数据编码Windows-1252。 在这种情况下,就会指定用 fiona.open: encoding='Windows-1252' 函数的 encoding 关键字参数来指定相应编码。版本为0.9.1。

5.1.1. 索引集

版本为1.1.6,也可通过指数进入特性集。

>>> from pprint import pprint
>>> with fiona.open('/gdata/prov_capital.shp') as src:
>>>     pprint(src[1])
<fiona.model.Feature object at 0x7fc00f4d1010>

5.1.2. 关闭文件

fiona.collection.Collection 包含外部资源。 除非用 with statement明确 fiona.collection.Collection.close 对象,否则不能保证资源会被释放。 当 fiona.collection.Collection 处于上下文管理器时,无论发生什么(是否有异常发生),都会被关闭。

>>> try:
>>>     with fiona.open('/gdata/prov_capital.shp') as c:
>>>         print(len(list(c)))
>>>         # assert True is False
>>> except:
>>>     print(c.closed)
>>>     raise
34

有一项特殊,当 with 模块raise时,你可以查看到输出表 exceptc.__exit__ (从而导致 c.close ) 。