You need to use QgsVectorFileWriter.writeAsVectorFormat
QgsVectorFileWriter.writeAsVectorFormat
.
If If you store one layer per GPKG file you just need:
QGIS 3:
# imports
from qgis.utils import iface
from qgis.core import QgsProject, QgsVectorFileWriter
# get layer list by one of:
lyrs = iface.layerTreeView().selectedLayers()
lyrs = QgsProject.instance().layerTreeRoot().children()
# select layer
lyr = lyrs[0]
_writer = QgsVectorFileWriter.writeAsVectorFormat(lyr, r"C:\gisData\layer.gpkg")
QGIS 2:
# imports
from qgis.utils import iface
from qgis.core import QgsMapLayerRegistry, QgsVectorFileWriter
# get layer list by one of:
#QGIS2
lyrs = iface.mapCanvas().layers() # OR
lyrs = QgsMapLayerRegistry.instance().mapLayers() # OR
#QGIS3
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 gkpgGeoPackage 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)
from qgis.core import QgsMapLayer, QgsVectorFileWriter
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 need to use other methods.