读取GIS矢量文件时,可用 Fiona的 open
函数,再用 'r'
参数打开。返回类型为 fiona.collection.Collection
。
import os
# os.environ['PROJ_LIB'] = '/usr/miniforge/envs/python312/share/proj'
import fiona
fiona.__version__
'1.10.1'
import fiona
c = fiona.open('/data/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.Feature(geometry=fiona.Geometry(coordinates=(87.57610577000008, 43.78176563200003), type='Point'), id='0', properties=fiona.Properties(name='乌鲁木齐', lat=43.7818, lon=87.5761))
len(list(c))
34
注:list
接口覆盖的是整个 collection
,就像操作 Python文件对象一样,可有效地清除它。对于遍历过的 collection
对象,不支持查找前面的文件,你必须重新打开集合,才可以返回初始部分。
c = fiona.open('/data/gdata/prov_capital.shp')
len(list(c))
34
from pprint import pprint
with fiona.open('/data/gdata/prov_capital.shp') as src:
pprint(src[1])
fiona.Feature(geometry=fiona.Geometry(coordinates=(91.16312837700008, 29.710352750000027), type='Point'), id='1', properties=fiona.Properties(name='拉萨', lat=29.7104, lon=91.1631))
try:
with fiona.open('/data/gdata/prov_capital.shp') as c:
print(len(list(c)))
# assert True is False
except:
print(c.closed)
raise
34
有一项特殊,当 with
模块raise时,你可以查看到输出表 except
、 c.__exit__
(从而导致 c.close
) 。