I need save selected attributes of layer as CSV with separator. This is my code:

def initAlgorithm(self, config=None):
        self.addParameter(QgsProcessingParameterVectorLayer('Input', 'Input', types=[QgsProcessing.TypeFile], defaultValue=None))
        self.addParameter(QgsProcessingParameterFeatureSink('Output', 'Output', type=QgsProcessing.TypeFile, createByDefault=True, defaultValue= '')) 

def processAlgorithm(self, parameters, context, model_feedback):
        feedback = QgsProcessingMultiStepFeedback(1, model_feedback)
        results = {}
        outputs = {}

        alg_params = {
            'FIELDS_MAPPING': [{'expression': 'FID',  
                                'length': 10, 
                                'name': 'FID',  
                                'precision': 0,
                                'type': 10},  
            'INPUT': parameters['Input'],
            'OUTPUT':  parameters['Output']
        results['Result'] = processing.run('qgis:refactorfields', alg_params, context=context, feedback=feedback, is_child_algorithm=True)
        outputs['Outputs'] = results['Result']['OUTPUT']
        crs = QgsCoordinateReferenceSystem("EPSG:5514")
        uri = outputs['Outputs']
        layer = QgsVectorLayer(uri, 'name', 'ogr' )
        QgsVectorFileWriter.writeAsVectorFormat(layer, 'C:/Users/xxxx/OneDrive/xxxx', "utf-8", crs, "CSV", layerOptions=["GEOMETRY=AS_YX", "SEPARATOR=SEMICOLON"])  
        return outputs

Problem is that the CSV is exported, but with comma not separator.

In layerOptions I have I want separator as delimiter, but it isn´t working. I can´t find mistake, maybe in Output?


1 Answer 1


Working on my side. I suppose there is a minor difference in your code that breaks your result

To confirm the issue is in your code and not related to QGIS version or specific install issue, you can try this standalone working solution by selecting a point layer and run in the console the following

layer = iface.activeLayer()
QgsVectorFileWriter.writeAsVectorFormat(layer, '/tmp/out_semicolon.csv', "utf-8", layer.crs(), "CSV", layerOptions=["GEOMETRY=AS_YX", "SEPARATOR=SEMICOLON"])

with open("/tmp/out_semicolon.csv") as infile:
    # To confirm you see semicolon separated result

QgsVectorFileWriter.writeAsVectorFormat(layer, '/tmp/out_tab.csv', "utf-8", layer.crs(), "CSV", layerOptions=["GEOMETRY=AS_YX", "SEPARATOR=TAB"])

with open("/tmp/out_tab.csv") as infile:
    # To confirm you see tab separated result

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.