Identifying polygon/point shapefiles in PyQGIS?

You need to open it as a QgsVectorLayer

 layer = QgsVectorLayer('/path/to/shapefile_folder/test.shp', 'test', 'ogr')

QgsVectorLayer objects have a method called geometryType. If you call that method for your newly created layer :

>>> print layer.geometryType()
2

Where 0 is points, 1 is lines and 2 is polygons


I guess the "proper" way is to use QGIS' API which I'd hope would expose that. But I don't know how to do that.


An alternative is to look without the shapefile itself. The basics of the specification are on Wikipedia: https://en.wikipedia.org/wiki/Shapefile#Shapefile_shape_format_.28.shp.29

What you want is: bytes 32–35 of the main header which dictates what the geometry type is. The values of this are integers and should be:

Value Shape Type
0 Null Shape
1 Point
3 PolyLine
5 Polygon
8 MultiPoint
11 PointZ
13 PolyLineZ
15 PolygonZ
18 MultiPointZ
21 PointM
23 PolyLineM
25 PolygonM
28 MultiPointM
31 MultiPatch

So all you need to do is parse the header of the file in Python to determine those.

For reference, the official Shapefile "Specification" (actually a white paper) is: http://www.esri.com/library/whitepapers/pdfs/shapefile.pdf