I have a vector file that contains multiple layers, if I open it in QGIS I get the "Select vector layers to add dialog" and I can choose one and it loads fine.

However in a .py script if I load it via

layer = QgsVectorLayer(filename, "mylayer", "ogr")

I just get one of the layers (layer 0)

How do I specify which layer I want to load? Or if it IS actually loading all of them, how do I change to the one I want?

My full script

import os
import sys
import qgis
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import ogr

qgs = QgsApplication([], False)
QgsApplication.setPrefixPath( r"C:\Program Files\QGIS 2.18\apps\qgis-ltr", True )

filename = "C:/datafiles/sourcefile"
if os.path.exists(filename):
    print('found it')

layer = QgsVectorLayer(filename, "mylayer", "ogr")
if layer.isValid(): 
    print("Layer was loaded successfully!")
    print("Layer failed to load!")

print (layer.type())
print (layer.name())
print (layer.id()) 


2 Answers 2


...and then five minutes later I stumble across the answer here iface.addVectorLayer on a gml file causes "Select vector layers to add" dialog (pyqgis)

You add


to the file path, giving:

filename = "C:/datafiles/sourcefile|layername=NameOfTheLayerYouWantToLoad"

Welcome to GIS.SE!

If you know the sublayer name already:

layer_path = '/path/to/base_layer.gpx' # GPX is just an example
sublayer_name = 'tracks'
uri = "{}|layername={}".format(layer_path, sublayer_name)
sublayer = QgsVectorLayer(uri, 'layer name', 'ogr')

If you want to know sublayer names given a layer (I'm not sure if there is a better way, though):

if len(layer.dataProvider().subLayers()) > 1:
    for subLayer in layer.dataProvider().subLayers():

Which will print something like:


Extracted from an array like this:


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.