2

Is it possible to pass Processing Tool native:mergevectorlayers to a QgsVectorFileWriter.writeAsVectorFormatV3 object

output_folder = r"/home/cirrusklaus/Downloads/tmp/csv/"
options = QgsVectorFileWriter.SaveVectorOptions()
options.driverName = "csv"
preFix = 'kon_'
lyrList = []

for lyr in QgsProject.instance().mapLayers().values():
    if lyr.name().startswith(preFix) and isinstance(lyr, QgsVectorLayer):
        lyrList.append(lyr.name())
        #path = os.path.join(output_folder, lyr.name()+'.csv')
        #QgsVectorFileWriter.writeAsVectorFormatV3(lyr, path, QgsCoordinateTransformContext(), options)
print(lyrList)
#########################################
#Merge wird vorbereitet und ausgeführt
parMerge = {
    'LAYERS': lyrList, #Layer aus der Layerliste werden übergeben
    'CRS': None,
    'OUTPUT': 'memory:'
    }
result1 = processing.runAndLoadResults("native:mergevectorlayers", parMerge)
ResMerge = result1['OUTPUT']

path = os.path.join(output_folder,'Tab'+'.csv')
options = QgsVectorFileWriter.SaveVectorOptions()
options.driverName = "csv"
options.fileEncoding = "utf-8"
transform_context = QgsProject.instance().transformContext()
QgsVectorFileWriter.writeAsVectorFormatV3(ResMerge, path, transform_context, options)
print("Finished")
2
  • Yes it is. Perhaps try 'OUTPUT':'TEMPORARY_OUTPUT' in the parameters. Commented May 1, 2023 at 4:41
  • that makes no difference, when I use the processing.runAndLoadResults("native:mergevectorlayers", parMerge) occurs the error
    – Klaus
    Commented May 1, 2023 at 6:37

1 Answer 1

4

The issue here is that when you call the processing.runAndLoadResults() method, the 'OUTPUT' value returned is a layer id string (as opposed to calling processing.run() which returns a QgsVectorLayer object).

So to get a vector layer object which you can pass to QgsVectorFileWriter.writeAsVectorFormatV3(), you can do the following:

Add to import statements:

from processing.tools import dataobjects

Then:

result1 = processing.runAndLoadResults("native:mergevectorlayers", parMerge)
ResMerge = result1['OUTPUT']
context = dataobjects.createContext()
v_lyr = QgsProcessingUtils.mapLayerFromString(ResMerge, context)

However, while this should answer your current question, I'm not sure why you don't just use an additional processing algorithm (native:savefeatures) to which you can pass the layer id string output from the previous processing alg.

output_folder = r"/home/cirrusklaus/Downloads/tmp/csv/"
preFix = 'kon_'
lyrList = []

for lyr in QgsProject.instance().mapLayers().values():
    if lyr.name().startswith(preFix) and isinstance(lyr, QgsVectorLayer):
        lyrList.append(lyr.name())
print(lyrList)
#########################################
#Merge wird vorbereitet und ausgeführt
parMerge = {
    'LAYERS': lyrList, #Layer aus der Layerliste werden übergeben
    'CRS': None,
    'OUTPUT': 'memory:'
    }
result1 = processing.runAndLoadResults("native:mergevectorlayers", parMerge)
ResMerge = result1['OUTPUT']
path = os.path.join(output_folder,'Tab.csv')
save_params = {'INPUT': ResMerge,
                'OUTPUT':path}
processing.run('native:savefeatures', save_params)
print("Finished")
5
  • 1
    thx Ben, I have learned some new PyQIS-Code
    – Klaus
    Commented May 1, 2023 at 6:42
  • @Klaus, great! You're welcome :-)
    – Ben W
    Commented May 1, 2023 at 6:46
  • At the beginning of the process I have shp-files at the end it should be a csv-file, therefore I use the object QgsVectorFileWriter.writeAsVectorFormatV3. If i use other processing tools, is the processing tool "processing.run('native:savefeatures', save_params)" to be used at the end or at each step of the process?
    – Klaus
    Commented May 1, 2023 at 7:09
  • @Klaus, not too sure what you mean. Just use it to write any temporary output layers which you want to save to a file location. You can use it after any other processing step or at the end of a chain of algorithms to save the output to a file location. It's simply a quick alternative to using the QgsVectorFileWriter class. Being a processing alg, it's quite versatile. The 'INPUT' param can be a path ('path/to/some.shp'), a QgsVectorLayer object or a layer id string.
    – Ben W
    Commented May 1, 2023 at 7:31
  • 1
    Of course, you can pass a file location as the output of any processing alg, I suggested save features here since you want to load the merged layer and save it as a csv.
    – Ben W
    Commented May 1, 2023 at 13:09

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.