inspired by https://gis.stackexchange.com/a/361296
import processing grouped_layers_by_name = {} distinct_layer_names = set() project_layers = [] for l in QgsProject.instance().layerTreeRoot().children(): project_layers += l.children() for layer_item in project_layers: layer_name = layer_item.name() distinct_layer_names.add(layer_name) grouped_layers_by_name[layer_name] = QgsProject.instance().mapLayersByName(layer_name) print('Total number of distinct layers: ' + str(len(distinct_layer_names))) for layer_name in distinct_layer_names: print('Processing layer: ' + layer_name + '...', end=' ') merged_layer_file_name = './5000/' + layer_name + '.gpkg' ls = grouped_layers_by_name.get(layer_name) if ls is None: continue print(ls) alg_params = {'LAYERS': ls, 'OUTPUT': merged_layer_file_name} result = processing.run('native:mergevectorlayers', alg_params) print(' done.') print('All layers have been merged.')