Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Print summary of string fields and values from a shapefile(or anything else OGR can read)
#!/usr/bin/env python
import logging
from optparse import OptionParser
import os
from osgeo import ogr
def log_file_fields(filename):
print("File: " + filename)
source = ogr.Open(filename)
for i in range(source.GetLayerCount()):
layer = source.GetLayerByIndex(i)
layerName = layer.GetName()
print("Layer: " + layerName)
stringFields = []
layerDefinition = layer.GetLayerDefn()
for n in range(layerDefinition.GetFieldCount()):
fieldDefinition = layerDefinition.GetFieldDefn(n)
fieldName = fieldDefinition.GetName()
fieldTypeCode = fieldDefinition.GetType()
fieldType = fieldDefinition.GetFieldTypeName(fieldTypeCode)
if fieldType == "String":
print("String Fields:")
for field in stringFields:
sql = 'SELECT %s FROM %s' % (field, layerName)
fieldLayer = source.ExecuteSQL(sql)
values = {}
for i, feature in enumerate(fieldLayer):
values[feature.GetField(0)] = values.get(feature.GetField(0), 0) + 1
print("Field: " + field)
for key in sorted(values.keys()):
print("'%s': %d" % (key, values[key]))
def _main():
usage = "usage: %prog"
parser = OptionParser(usage=usage,
parser.add_option("-d", "--debug", action="store_true", dest="debug",
help="Turn on debug logging")
parser.add_option("-q", "--quiet", action="store_true", dest="quiet",
help="turn off all logging")
(options, args) = parser.parse_args()
logging.basicConfig(level=logging.DEBUG if options.debug else
(logging.ERROR if options.quiet else logging.INFO))
for arg in args:
if __name__ == "__main__":

This comment has been minimized.

Copy link
Owner Author

@JesseCrocker JesseCrocker commented Oct 27, 2017

Example output:

File: /Users/jesse/projects/public-land/nps_boundary/nps_boundary.shp
Layer: nps_boundary
String Fields:
'ABLI': 1
'ACAD': 1
'ADAM': 1
'AFBG': 1
'AGFO': 1
'ALAG': 1
'ALFL': 1
'ALKA': 1

Field: GIS_Notes
'Digitzed from TerraServer DOQQ': 1
'Generated from APPA centerline (Casey Reese)  buffered 500 feet': 1
'Generated from NHDFlowline high resolution feature class': 1
'LEGACY: NPS Inventory and Monitoring Program Data from 2008': 46
'LEGACY: contact for additional information': 11
'LEGACY: contact for additional information': 1
'Lands': 1
'Lands -': 1
'Lands -': 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment