3

I inherited some code for a QGIS Python plugin which uses the ogr module. For each usage of ESRI Shapefiles is hardcoded due to the loading of the respective driver (ogr.GetDriverByName("ESRI Shapefile")).

I want to be agnostic to the vector filetype, e.g. allow .gpkg as well. Is there a clean way to let ogr decide by itself, which driver to use (e.g. choosing by file extension).

from osgeo import ogr

driver = ogr.GetDriverByName("ESRI Shapefile")
dataSource = driver.Open(vector_file_path, 1)
layer = dataSource.GetLayer()

I found to my surprise no example for this so far, no cookbook entry and also didn't learn anything conclusive from the doc.

I'd simply use the layer = QgsVectorLayer(vector_file_path), however a lot of the following code is tailored to use ogr and rather than rewriting everything I'd simply adjust the head to allow for gpkg and other vector formats, if possible.

1
  • Did you try looking to see how QGis does it?
    – Ian Turton
    Mar 2 at 0:57

2 Answers 2

2

The cookbooks are apparently a bit dated, but yes, this is possible. Some more up-to-date information can be found in the GDAL Vector API Tutorial.

The following should do the trick:

Replace

from osgeo import ogr

driver = ogr.GetDriverByName("ESRI Shapefile")
dataSource = driver.Open(vector_file_path, 1)

by

from osgeo import gdal

dataSource = gdal.OpenEx(vector_file_path, 1)
driver = dataSource.GetDriver()
drivername = driver.ShortName

Edit: added getting the driver/driver name if you would need it, in answer to the comment of @user30184.

4
  • Great that works. I noticed that my predecessor used dataSource.Destroy() to close the dataSource object created with dataSource = driver.Open(vector_file_path, 1). Is there an equivalent necessary?
    – Honeybear
    Mar 3 at 7:28
  • I found it myself; dataSource.Close() would be the equivalent.
    – Honeybear
    Mar 3 at 8:26
  • Yes, you can still use datasource.Destroy, but other ways to deal with it are recommended as explained here.
    – Pieter
    Mar 3 at 8:38
  • great, thanks for pointing that out - I wasn't aware that gdal supports the with context, but read (apparently old) comments that it doesn't during my research for this question.
    – Honeybear
    Mar 7 at 8:12
0

As Pieter answered, OpenEx can do it. If you want to know what driver gets selected you can do it for example with the library version of ogrinfo.

from osgeo import gdal
ds = gdal.OpenEx("test.gml")
ret = gdal.VectorInfo(ds, format="json")
print(ret["driverShortName"])
GML
2
  • 1
    or with driver = ds.GetDriver().ShortName
    – Pieter
    Mar 2 at 13:10
  • 1
    Better that way, but I left the VectorInfo option as an alternative.
    – user30184
    Mar 2 at 13:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.