View Shapefile Contents Using Python Without ArcMap License – How to Guide

pythonshapefile

I wondered if it is possible to look at the contents of a shapefile using Python without having and ArcMap license. The situation is that you can create shapefiles from many different applications, not only from ESRI software. I would like to create a Python script that checks the spatial reference, feature type, attribute names and definitions, and the contents of the fields in a shapefile and compares them to a set of acceptable values. I would like this script to work even if the organization does not have any ESRI licenses. To do something like this, do you have to use ArcPy or can you dig into a shapefile without using ArcPy?

Best Answer

I would recommend becoming familiar with the Python GDAL/OGR API to work with both vector and raster data. The easiest way to start using GDAL/OGR is via a python distribution such as python(x,y), Anaconda, or OSGeo4W.

Further details on using GDAL for your specific tasks:

Additionally, I would recommend the following tutorial from USU to get you started.


Borrowing from the examples above, the following script uses FOSS tools to perform the following actions:

  1. Check the spatial reference
  2. Get shapefile fields and types
  3. Check if rows in a user-defined field contain some value

# Import the necessary modules
from  osgeo import ogr, osr

driver = ogr.GetDriverByName('ESRI Shapefile')
shp = driver.Open(r'C:\your\shapefile.shp')

# Get Projection from layer
layer = shp.GetLayer()
spatialRef = layer.GetSpatialRef()
print spatialRef

# Get Shapefile Fields and Types
layerDefinition = layer.GetLayerDefn()

print "Name  -  Type  Width  Precision"
for i in range(layerDefinition.GetFieldCount()):
    fieldName =  layerDefinition.GetFieldDefn(i).GetName()
    fieldTypeCode = layerDefinition.GetFieldDefn(i).GetType()
    fieldType = layerDefinition.GetFieldDefn(i).GetFieldTypeName(fieldTypeCode)
    fieldWidth = layerDefinition.GetFieldDefn(i).GetWidth()
    GetPrecision = layerDefinition.GetFieldDefn(i).GetPrecision()
    print fieldName + " - " + fieldType+ " " + str(fieldWidth) + " " + str(GetPrecision)

# Check if rows in attribute table meet some condition
inFeature = layer.GetNextFeature()
while inFeature:

    # get the cover attribute for the input feature
    cover = inFeature.GetField('cover')

    # check to see if cover == grass
    if cover == 'trees':
        print "Do some action..."

    # destroy the input feature and get a new one
    inFeature = None
    inFeature = inLayer.GetNextFeature()