Search code examples
pythonpython-2.7gisshapelyfiona

using python to verify that a shapefile is a shapefile (fiona, ogr)


On fiona 1.5.0 (I am getting confused why various files (such as .dbf and a .gdb) are not printing my "Not a Shapefile!" (which is what I want ANYTIME that the file is not a .shp) warning before exiting.

import fiona
import sys

   def process_file(self, in_file, repair_file):
        with fiona.open(in_file, 'r', encoding='utf-8') as input:
            # check that the file type is a shapefile
            if input.driver == 'ESRI Shapefile':
                print "in_file is a Shapefile!"
            else:
                print "NOT a Shapefile!"
                exit()
            with fiona.open(repair_file, 'r') as repair:
                # check that the file type is a shapefile
                if repair.driver == 'ESRI Shapefile':
                    print "Verified that repair_file is a Shapefile!"
                else:
                    print "NOT a Shapefile!"
                    exit()

For a gdb I get an error that fiona doesn't support the driver (since ogr does that surprised me)- and no print statement:

>> fiona.errors.DriverError: unsupported driver: u'OpenFileGDB'

For a .dbf I actually get this:

>> Verified that in_file is a Shapefile!
>> Verified that repair_file is a Shapefile!

Solution

  • With OGR, the ESRI Shapefile driver reads DBF files. To check if the data source has only attributes, and no geometry (i.e., just a DBF file), check the geometry type in the metadata to see if it is 'None'.

    import fiona
    with fiona.open(file_name) as ds:
        geom_type = ds.meta['schema']['geometry']
        print('geometry type: ' + geom_type)
        if geom_type == 'None':
            print('no geometry column, so probably just a DBF file')
    

    Also, read-only support for OpenFileGDB was recently added to fiona. Update your package and see if it works.