1) shapefile individual: como no comentário, um shapefile possui apenas uma camada. Se você deseja apenas os nomes dos campos
from osgeo import ogr
source = ogr.Open("a_shapefile.shp")
layer = source.GetLayer()
schema = []
ldefn = layer.GetLayerDefn()
for n in range(ldefn.GetFieldCount()):
fdefn = ldefn.GetFieldDefn(n)
schema.append(fdefn.name)
print schema
['dip_dir', 'dip', 'cosa', 'sina']
Você pode usar o formato GeoJSON com um gerador Python ( ogr_geointerface.py )
def records(layer):
# generator
for i in range(layer.GetFeatureCount()):
feature = layer.GetFeature(i)
yield json.loads(feature.ExportToJson())
features = record(layer)
first_feat = features.next()
print first_feat
{u'geometry': {u'type': u'Point', u'coordinates': [272070.600041, 155389.38792]}, u'type': u'Feature', u'properties': {u'dip_dir': 130, u'dip': 30, u'cosa': -0.6428, u'sina': -0.6428}, u'id': 0}
print first_feat['properties'].keys()
[u'dip', u'dip_dir', u'cosa', u'sina']
Isso apresenta o Fiona (outro wrapper Python do OGR, Python 2.7.xe 3.x). Todos os resultados são dicionários Python (formato GeoJSON).
import fiona
shapes = fiona.open("a_shapefile.shp")
shapes.schema
{'geometry': 'Point', 'properties': OrderedDict([(u'dip_dir', 'int:3'), (u'dip', 'int:2'), (u'cosa', 'float:11.4'), (u'sina', 'float:11.4')])}
shapes.schema['properties'].keys()
[u'dip', u'dip_dir', u'cosa', u'sina']
# first feature
shapes.next()
{'geometry': {'type': 'Point', 'coordinates': (272070.600041, 155389.38792)}, 'type': 'Feature', 'id': '0', 'properties': OrderedDict([(u'dip_dir', 130), (u'dip', 30), (u'cosa', -0.6428), (u'sina', -0.6428)])}
E GeoPandas (Fiona + pandas , Python 2.7.xe 3.x). O resultado é um DataFrame do Pandas (= GeoDataFrame).
import geopandas as gpd
shapes = gpd.read_file("a_shapefile.shp")
list(shapes.columns.values)
[u'dip', u'dip_dir', u'cosa', u'sina', 'geometry']
# first features
shapes.head(3)
2) Vários shapefiles: se você deseja percorrer vários shapefiles em uma pasta
Com osgeo.ogr
for subdir, dirs, files in os.walk(rootdir):
for file in files:
if file.endswith(".shp"):
source = ogr.Open(os.path.join(rootdir, file))
layer = source.GetLayer()
ldefn = layer.GetLayerDefn()
schema = [ldefn.GetFieldDefn(n).name for n in range(ldefn.GetFieldCount())]
print schema
ou com um gerador
def records(shapefile):
# generator
reader = ogr.Open(shapefile)
layer = reader.GetLayer(0)
for i in range(layer.GetFeatureCount()):
feature = layer.GetFeature(i)
yield json.loads(feature.ExportToJson())
for subdir, dirs, files in os.walk(rootdir):
for file in files:
if file.endswith(".shp"):
layer = records(os.path.join(rootdir, file))
print layer.next()['properties'].keys()
Com Fiona
import fiona
for subdir, dirs, files in os.walk(rootdir):
for file in files:
if file.endswith(".shp"):
layer = fiona.open(os.path.join(rootdir, file))
print layer.schema['properties'].keys()