I have ~ 4000 geopackages of which each comes with many layers. The goal is to be able to select two layers from each geopackage, merge them into one layer and export the merged layers as geopackage with only one layer. So in the end I will have ~4000 geopackages of which each includes only one layer.
I know that I can use the QGIS-native function mergevectorlayers
to merge two vector layers like this:
processing.run("native:mergevectorlayers",
{'LAYERS': [layer1,layer2],'CRS':QgsCoordinateReferenceSystem('EPSG:...'),
'OUTPUT':definedOutputpathAsString})
But as for the LAYERS-parameter I need to create a list from two layers selected from a geopackage, as described above.
How can I select the two relevant layer from a geopackage and create QgsVectorLayer for each of them?
1 Answer 1
I did find an answer myself.
The following line of code takes the relevant layer from the geopackage by its name ( here as example the layer's name is 'building') and creates a QgisVectorLayer-object from it.
from qgis.core import *
import os
import processing
from processing.core.Processing import Processing
Processing.initialize()
rel_layername = 'building'
layer = QgsVectorLayer(file_path+"|layername=" + rel_layername, 'layer_name','ogr')
For this, you need to know the layer's name.
UPDATE
Just if someone is interested in selecting certain layers by it's name from geopackage, merging them and then exporting as new geopackage, this is the final code:
from qgis.core import *
import os
import processing
from processing.core.Processing import Processing
Processing.initialize()
from osgeo import ogr
def gpkgLayerToQgsVectorLayer(gpkg_path, layername):
layers = [l.GetName() for l in ogr.Open(gpkg_path)]
if layer in layers:
layer = QgsVectorLayer(gpkg_path+"|layername=" + layername, 'layer_name', 'ogr')
return layer
else:
print(f'Error: there is no layer named {layername} in {gpkg_path}!')
def mergeRelevantBuildings(folderpath, outputfolderpath):
for filename in os.listdir(folderpath):
if '.gpkg' in filename:
filepath = f'{folderpath}/{filename}'
print(filepath)
outputfilepath = f'{outputfolderpath}/{filename}'
print(outputfilepath)
buildings = gpkgLayerToQgsVectorLayer(filepath, 'building')
others = gpkgLayerToQgsVectorLayer(filepath, 'consistsofbuildingpart')
layers = [buildings,others]
processing.run(
"native:mergevectorlayers",
{'LAYERS': layers,
'CRS':QgsCoordinateReferenceSystem("EPSG:25832"),
'OUTPUT':outputfilepath}
)