6

I have problems to save a vector layer at QGIS 3.0 with his original name in a GeoPackage.

from qgis.utils import iface
from qgis.core import QgsVectorFileWriter

canvas = iface.mapCanvas() layer = canvas.currentLayer() writer = QgsVectorFileWriter.writeAsVectorFormat(layer, "V:/test_layer/test_gpkg", 'utf-8', layer.crs(), "GPKG")

With this code I create a Geopackage with the selected vectorlayer in it. The only Problem is that the saved vectorlayer has the same name as the GeoPackage.

Can somebody help me to save the vectorlayer in a different name than the GeoPackage and maybe how to add other vectorlayers?

Taras
  • 32,823
  • 4
  • 66
  • 137
RickJames
  • 189
  • 9

1 Answers1

7

This post: Adding layer to GeoPackage using PyQGIS solves your problem but to be a pure answer to your question, try in this way:

from qgis.utils import iface
from qgis.core import QgsVectorFileWriter

canvas = iface.mapCanvas() layer = canvas.currentLayer()

options = QgsVectorFileWriter.SaveVectorOptions() options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteLayer

to get rid of spaces in the layer name

options.layerName = "_".join(layer.name().split(' '))

writer = QgsVectorFileWriter.writeAsVectorFormat(layer, "V:/test_layer/test_gpkg", options)

Taras
  • 32,823
  • 4
  • 66
  • 137
Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389