I can use the following to add multiple shapefiles to QGIS:

import os, glob

shape_path = "C:\Users\Me\Desktop\Test\Shapefiles\\"
for shape in glob.glob(shape_path + "*.shp"):
    layer = QgsVectorLayer(shape, os.path.basename(shape), "ogr")

However, I have dozens of .gdb folders which I would like to add automatically (I can do this individually through Layer > Add Vector Layer but would be quite tedious).

Is there a similar, or albeit another, method using PyQGIS to add multiple GDB files?

  • Change .shp to .GDB? – Nathan W Oct 8 '15 at 10:31
  • @NathanW - Thanks Nathan but already tried that, didn't work. – Joseph Oct 8 '15 at 10:33
  • 1
    File geodatabase is a container, not a data file. There could be many (hundreds, thousands, millions) tables within that container, and some of them may not have geometry. – Vince Oct 8 '15 at 14:30
  • @Vince - Thanks Vince for adding that, it makes it a lot more clear. You're right in that there's quite a few tables within each container that I have, hence the 'need' to add them programmatically :) – Joseph Oct 8 '15 at 14:36

This aims to be a generic answer.

If you are able to load a layer in QGIS you can query its uri through the python console:


in the printed uri you can easily tell, which part of the uri should be dynamically created and write python logic that substitutes this part, e.g. with glob results.

The first parameter passed to the QgsVectorLayer constructor is nothing but this uri. The second parameter is the human readable layer name, the third parameter a provider key. The provider key can be queried with


For .gdb the provider key is also 'ogr'.

> iface.activeLayer().dataProvider().dataSourceUri()
> l=QgsVectorLayer(u'/home/user/geodata/demo.gdb|layername=TOWNSSURVEY_POLYM', 'survey', 'ogr' )
> l.isValid()
> QgsMapLayerRegistry.instance().addMapLayers([l])
[<qgis._core.QgsVectorLayer object at 0x7f8c7610a808>]
  • Turns out I just needed to set the path before using glob but I will accept your answer as it provides a more educational description :) – Joseph Oct 8 '15 at 12:17
  • 1
    Strange, that should not be required (i.e. imagine QGIS changing its pwd whenever a new layer is added). I did not have to call os.chdir, see the pasted excerpt which works for me. – Matthias Kuhn Oct 8 '15 at 12:41
  • Thank you, your code also works for me. Good to know another method :) – Joseph Oct 8 '15 at 12:49

You can use the practically similar method for shapefiles but the path must be set before using glob:

import os, glob

for fname in glob.glob("*.gdb"):
    layer = QgsVectorLayer(fname, os.path.basename(fname), "ogr")

Hope this helps others!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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