4

I made my first working script by selecting features on a layer with the Python console. Now i want to export the selected features to a GML or GPKG, but i cannot find any info on how to do so.

I did find SHP, but that causes Qgis to become unresponsive. Is there any way that i can do this?

The original file from which i made the selections is a CityGML, i do not know if that causes any issues. I would like to be able to this regardless of original file type.

Hope somebody can help me out

It did export, but there was nothing in the layer... Also it took forever, but when i manually export the selection its done in a second

layer = QgsProject.instance().mapLayersByName("bgt_wegdeel TrafficArea")[0]
iface.setActiveLayer(layer)
layer.selectByExpression( "\"function\"='rijbaan regionale weg'" )

fn = 'D:\ExportTest\Regionaleweg'
writer = QgsVectorFileWriter.writeAsVectorFormat(layer, fn, 'utf-8', \
driverName='GPKG', onlySelected=True)
3
  • Can you share some of the code you tried?
    – JonasV
    Jul 30, 2021 at 8:25
  • It did export, but there was nothing in the layer... Also it took forever, but when i manualy export the selection its done in a second layer = QgsProject.instance().mapLayersByName("bgt_wegdeel TrafficArea")[0] iface.setActiveLayer(layer) layer.selectByExpression( "\"function\"='rijbaan regionale weg'" ) fn = 'D:\ExportTest\Regionaleweg' writer = QgsVectorFileWriter.writeAsVectorFormat(layer, fn, 'utf-8', \ driverName='GPKG', onlySelected=True)
    – Ermin0s
    Jul 30, 2021 at 8:52
  • what happens if you define the exportfile (not only the folder) and the crs?: fn = 'D:\ExportTest\Regionaleweg\export.gpkg' writer = QgsVectorFileWriter.writeAsVectorFormat(layer, fn, 'utf-8', \ layer.crs(), driverName='GPKG', onlySelected=True)
    – Thomas B
    Jul 30, 2021 at 9:40

1 Answer 1

6

When I used writeAsVectorFormat to save a CityGML layer, it didn't work. I don't know why. But the "Save vector features to file" tool works.

layer = QgsProject.instance().mapLayersByName("TrafficArea")[0]
layer.selectByExpression( "\"function\"='rijbaan regionale weg'" )

source = layer.source()
output = r'D:\ExportTest\Regionaleweg\output.gpkg'

processing.run(
    "native:savefeatures",
    {
        'INPUT': QgsProcessingFeatureSourceDefinition(
            source,
            selectedFeaturesOnly=True),
        'LAYER_NAME': layer.name(),
        'OUTPUT': output
    }
)

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.