I'm trying to export a shapefile layer to KML format in QGIS , trough Python coding.

The code is:

QgsVectorFileWriter.writeAsVectorFormat(inputlayer, outputlayer, "utf-8", coord_system, "KML")

But I have to add dataSourceOption in the line, because I have to specify a "nameField".

How I can add dataSourceOption in the writeAsVectorFormat method? I have see that dataSourceOption accept a QStringList() but I don't understand.


2 Answers 2


datasourceOptions are passed as a list of OGR creation options for the format.

There are 2 ways: writeAsVectorFormatV2() and writeAsVectorFormat().

The first one is more neat in my opinion:

options = QgsVectorFileWriter.SaveVectorOptions()
options.driverName = "KML"
options.fileEncoding = 'utf-8'
options.datasourceOptions = ["NameField=ulica"]

QgsVectorFileWriter.writeAsVectorFormatV2(layer=inputLayer, fileName=fileName, transformContext=QgsCoordinateTransformContext(), options=options)

Second option:


PS. How I found the answer to your question:

Here is the documentation of QgsVectorFileWriter. The datasourceOptions parameter is described as a list of OGR data source creation options.

Here I looked up KML format Creation options in the GDAL/OGR documentation. Every format has its own specific creation options. If you need to specify any other options you just pass them in the list just as you would pass them if you used OGR/GDAL in command line.


Editing the name of one of the field of shapefile to "NAME" that is the default field take by the writer of the QgsVectorFileWriter.writeAsVectorFormat.

  • Please approve my answer :). I spent some time looking for this and it is the correct approach to your problem Commented Oct 22, 2020 at 6:25

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.