I'm trying to automate the process of exporting around 20 shapefiles from my QGIS project into a single GeoPackage using PyQGIS. Here is the code:
import os
from qgis.core import (
QgsProject,
QgsVectorFileWriter,
QgsCoordinateTransformContext,
QgsVectorLayer
)
output_gpkg = "C:/Users/kk/Desktop/QGIS/PyQGIS/CODES/output.gpkg"
if os.path.exists(output_gpkg):
os.remove(output_gpkg)
transform_context = QgsCoordinateTransformContext()
options = QgsVectorFileWriter.SaveVectorOptions()
options.driverName = "GPKG"
options.fileEncoding = "UTF-8"
for layer in QgsProject.instance().mapLayers().values():
if isinstance(layer, QgsVectorLayer) and layer.source().lower().endswith(".shp"):
options = QgsVectorFileWriter.SaveVectorOptions()
options.driverName = "GPKG"
options.fileEncoding = "UTF-8"
options.layerName = layer.name()
options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteLayer
error = QgsVectorFileWriter.writeAsVectorFormatV3(
layer,
output_gpkg,
transform_context,
options
)
if error[0] == QgsVectorFileWriter.NoError:
print(f"Successfully exported '{layer.name()}' to GeoPackage!")
else:
print(f"Export failed for '{layer.name()}': {error[1]}")
Although the code works sometimes, I keep getting this error:
Opening of data source in update mode failed (OGR error)