How to add layers (vector or raster to an existing GeoPackage)?

While loading an existing layer of a GeoPackage is quite trivial:

path = '/home/matteo/geopackage.gpkg|layername={}'.format('admin')
iface.addVectorLayer(path, 'admin', 'ogr')

I couldn't find information about adding them via PyQGIS.

Is it possible? Will it also work for rasters?


You need to use QgsVectorFileWriter.writeAsVectorFormat. If you store one layer per GPKG file you just need:

# get layer list by one of:
lyrs = iface.mapCanvas().layers() # OR
lyrs = QgsMapLayerRegistry.instance().mapLayers() # OR
lyrs = iface.layerTreeView().selectedLayers()
lyrs = QgsProject.instance().mapLayers()
lyrs = QgsProject.instance().layerTreeRoot().children()

# select layer
lyr = lyrs[0]
_writer = QgsVectorFileWriter.writeAsVectorFormat(lyr, r"C:\gisData\layer.gpkg")

If you want save more than one layer in gkpg file you should set additional options.

for lyr in filter(lambda l: l.type() == QgsMapLayer.VectorLayer, lyrs):
    options = QgsVectorFileWriter.SaveVectorOptions()
    options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteLayer 
    options.layerName = "_".join(lyr.name().split(' '))
    _writer = QgsVectorFileWriter.writeAsVectorFormat(lyr, gpkgPath, options)
    if _writer:
        print(lyr.name(), _writer)

PyQGIS should have similar interface for raster layers. In my opinion easiest way to find out is to install IPyConsole plugin and use PyQGIS API

EDIT 02/2020: As @MatthiasKuhn mentioned, to get list of layers in QGIS3 you nedd to use other methods.

| improve this answer | |
  • QgsMapLayerRegistry is gone in QGIS 3, but writeAsVectorFormat should still be there. Sidenote, there is also the QgsVectorLayerExporter class available. – Matthias Kuhn Nov 2 '18 at 7:38

I have investigated this code an create a script like it works very well for exporting raster layer to geopackage:

ds = ogr.Open(self.projectGpkg, True)
source = QgsRasterLayer(layerSource, 'rasterLayer', 'gdal')
if source.isValid():
    provider = source.dataProvider()
    fw = QgsRasterFileWriter(self.projectGpkg)
    fw.setCreateOptions(["RASTER_TABLE=" + str(tableName), 'APPEND_SUBDATASET=YES'])

    pipe = QgsRasterPipe()
    if pipe.set(provider.clone()) is True:
        projector = QgsRasterProjector()
        projector.setCrs(provider.crs(), provider.crs())
        if pipe.insert(2, projector) is True:
            if fw.writeRaster(pipe, provider.xSize(),provider.ySize(),provider.extent(),provider.crs()) == 0:
ds = None

For reading raster layer in geopackage:

rlayer = QgsRasterLayer('GPKG:' + str(self.projectGpkg) + ':tableName', "layerName")
| improve this answer | |

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.