1

For some reason my code is not doing what I expect it to do.

from qgis.core import *
from qgis.utils import iface
import processing

# Load the layer
layer = iface.mapCanvas().currentLayer()

bluespaces = QgsExpression ( " \"ITEM2012\" = 'Wetlands' OR \"ITEM2012\" = 'Water'")
selection = layer.getFeatures(QgsFeatureRequest(bluespaces))
ids = ([k.id() for k in selection])
layer.setSelectedFeatures( ids )
newlayer = QgsVectorFileWriter.writeAsVectorFormat(layer, 
               'U:\PythonTest\bluespaces.shp', 'System', 
               QgsCoordinateReferenceSystem(25382), 'ESRI Shapefile', bool(True))

This should give me a shapefile containing the blue spaces from the input layer. It works fine with other selection criteria and I checked if something was wrong with the selection criteria used above numerous times, but to no avail.

Can someone tell me what I am doing wrong?

  • Okay, I figured out that it has something to do with the first letter. When I safe it as "zluespaces", it works fine. Can someone explain this to me? – Jeroen vd Zand Jul 17 '18 at 9:56
2

Yes, \b is a special character for backspace. That's why. You should use a raw string (r in front of the path name) in this case.

newlayer =  QgsVectorFileWriter.writeAsVectorFormat(layer, 
                r'U:\PythonTest\bluespaces.shp', 'System', 
                QgsCoordinateReferenceSystem(25382), 'ESRI Shapefile', bool(True))

The computer recognizes the special characters instead of the path, example "C:\newFolder" is not correct because \n is the special character for a new line (enter). To tell that you want the string as it is you have to use the r in front of the path name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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