I would like to programmatically filter a layer based on its attributes and then export this filtered layer to KML file. In the example below, I have a layer called 'conduit' that I attempt to filter where status = AB. I then try to export this filtered layer to KML file. When I run the export, the full, unfiltered layer is exported.

def get_layer_by_name_quick(namepattern):
    layers = []
    for lyr in QgsProject.instance().mapLayers().values():
        if namepattern in str(lyr.name()):
    if len(layers) == 0:
        print(f"No Layer named  : {namepattern}")
        return None
    elif len(layers) > 1:
        print(f"multiple layers returned: \nnamepattern: {namepattern}, \nlayers: {layers}\n")
        return layers[0]
        return layers[0]

# get the layer named conduit
conduit_layer = get_layer_by_name_quick('CONDUIT')

# filter the layer for status = AB
expression = "status = 'AB'"

# write the output to kml file
output_layer = r"C:\path\to\file\file.kml"
QgsVectorFileWriter.writeAsVectorFormat(conduit_layer, output_layer, "utf-8", conduit_layer.crs(), "KML")

In fact, when I try to filter the layer via conduit_layer.setSubsetString(expression), I do not see the changes reflected in the map canvas. I would expect to see a filter symbol next to the layer name in the table of contents indicating that it is being filtered and I would expect to the see only the "AB status" conduit displayed on the map.

This is not what occurs. conduit_layer.setSubsetString(expression) returns a value of "True" and does not provide a handle that I can use to reference the filtered layer after the query is run.

How do I filter a layer based on attributes and then export the filtered result to a KML file?

Can you provide any additional information on how to specify the layer attributes during the export process?

For example, I'd like to be able to specify that no attributes are saved during the export to KML or I would like to specify a few by their field name if possible. The documentation has not helped me resolve this yet. From QGIS exporting attributes in a KML file I understand there is a way to do this using the GUI, but I am looking to do it via Python.

The code above actually works. I mistakenly thought it was not exporting the filtered layer, but after comparing to an export done via the GUI, the result is the same and the exported layer is indeed filtered.

1 Answer 1



QgsVectorFileWriter.writeAsVectorFormat(conduit_layer, output_layer, "utf-8", conduit_layer.crs(), "KML")


# Select by expression
conduit_layer.selectByExpression("status = 'AB'")
result = processing.run("native:saveselectedfeatures", {
    'INPUT': conduit_layer,
    'OUTPUT': output_layer
# If you want to add the result to check it works
iface.addVectorLayer(result['OUTPUT'], 'outputname', 'ogr')

Then, remove selection with

  • Thanks for the help. This exported a layer that contained no data for some reason. Upon further inspection - it looks like my original code worked as intended. I compared exporting from the GUI vs. exporting programmatically and the result is the same.
    – unbutu
    Aug 3, 2021 at 12:55
  • Updated my answer as I've made a wrong mix between layer selection and layer filtering in my initial answer. Tell me if alternative works.
    – ThomasG77
    Aug 3, 2021 at 13:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.