本文主要介绍使用GDAL-Python读取GDB格式数据,获取GDB中各图层的数据,读取过程与上一篇介绍的读取shp文件的方式类似,代码中已包含必要的注释。
import sys
from osgeo import ogr
driver = ogr.GetDriverByName('OpenFileGDB')
# GDB文件路径
file_name = 'D:/xxx.gdb'
# Open方法第二个参数0表示只读
data_source = driver.Open(file_name, 0)
# 根据数据源获取图层个数,遍历各图层,打印图层名
for index in range(data_source.GetLayerCount()):
layer = data_source.GetLayer(index)
# 打印各图层名
print(layer.GetName())
for feature in layer:
# 要素字段名集合
keys = feature.keys()
for key in keys:
# 要素字段值
value = feature.GetField(fieldName)
print("{}-->{}".format(key, value))
# 图形字段
geometry = feature.geometry()
print(geometry)
import sys
from osgeo import ogr
# GDB文件路径
file_name = 'D:/xxx.gdb'
# 加载OpenFileGDB驱动
driver = ogr.GetDriverByName('OpenFileGDB')
data_source = driver.Open(file_name, 0)
if data_source is None:
print("文件【%s】无法打开", file_name)
sys.exit(-1)
# 遍历各图层
for index in range(data_source.GetLayerCount()):
layer = data_source.GetLayer(index)
print("图层名:", layer.GetName())
for feature in layer:
# 要素字段名集合
keys = feature.keys()
for key in keys:
# 要素字段值
value = feature.GetField(fieldName)
print("{}-->{}".format(key, value))
# 图形字段
geometry = feature.geometry()
print(geometry)
del data_source