2

I want to create a GeoPackage file using PyQGIS (for example database.gpkg) with one layer (named "myLayer") not having any QgsVectorLayer at all.

I've tried this:

from qgis.core import QgsVectorFileWriter

writer = QgsVectorFileWriter(fileName, 'UTF-8', layerFields, QgsWkbTypes.Unknown, QgsProject.instance().crs(), 'GPKG', newLayer='myLayer')

but got an error:

('newLayer' is an unknown keyword argument)

I can't use writeAsVectorFormatV2 because I need to create a file first and then add it to QGIS.

2
  • 1
    @JGH no, this answer for saving exiting layers to geopackage and i know how to do this. But i need to create a geopackage first and then add it to Qgis.
    – BlackTesta
    Commented Jun 10, 2021 at 16:57
  • 2
    Germán Carrillo's answer does just that: in a single step, it creates the geopackage and saves the layer
    – JGH
    Commented Jun 10, 2021 at 17:24

1 Answer 1

2

Finally, I found the solution. This example creates a GeoPackage file with one geometryless layer without fields. The last line is necessary for the completion of file creation.

from qgis.core import QgsVectorFileWriter, QgsCoordinateTransformContext

file_path = 'd:\\test.gpkg'
options = QgsVectorFileWriter.SaveVectorOptions()
options.layerName = 'my_layer'
transform_context = QgsCoordinateTransformContext()
writer = QgsVectorFileWriter.create(file_path, QgsFields(), QgsWkbTypes.Unknown, QgsProject.instance().crs(), transform_context, options)
del writer

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.