I'm doing Open Source Options' tutorial on the topic but my code doesn't work. I guess the selectByExpression() works but writeAsVectorFormat() doesn't.

This is my code

layers = QgsProject.instance().mapLayersByName('Municipalities')
layer = layers[0]
layer.selectByExpression('"NAME_1"=Camarines Sur')
fn = r'C:\Users\imper\Documents\new_GISfiles\pyQGIS_practice\camSur.shp'
writer = QgsVectorFileWriter.writeAsVectorFormat(layer, fn, 'utf-8', \
QgsCoordinateReferenceSystem(32651), driverName='ESRI Shapefile', onlySelected=True)
selected_layer = iface.addVectorLayer(fn, '', 'ogr')

It runs but the result is a blank shapefile. What is wrong with my code when it's just copied from the tutorial? enter image description here

1 Answer 1


Try changing layer.selectByExpression('"NAME_1"=Camarines Sur') to layer.selectByExpression(" \"NAME_1\" = 'Camarines Sur'")

Basically, your issue is that your select statement doesn't work as you don't have quotes around your text. To fix this you can escape the quotes with backslashes around the attribute name and add apostrophes around the value you want to select.

Lastly, you are writing the layer incorrectly. Remove the writer variable and add the line:

QgsVectorFileWriter.writeAsVectorFormat( layer, fn, "utf-8", layer.crs(), "ESRI Shapefile", 1)

The variable one at the end is the boolean for True in this

final code:

layers = QgsProject.instance().mapLayersByName('Municipalities') layer = layers[0] layer.selectByExpression(" \"NAME_1\" = 'Camarines Sur'")

fn = r'C:\Users\imper\Documents\new_GISfiles\pyQGIS_practice\camSur.shp' QgsVectorFileWriter.writeAsVectorFormat( layer, fn, "utf-8", QgsCoordinateReferenceSystem(32651), "ESRI Shapefile", 1)

selected_layer = iface.addVectorLayer(fn, '', 'ogr')

  • Ok. Now I understand. Thank you! @jdavid05
    – BallpenMan
    Jul 8, 2020 at 1:41

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.