3

I am trying to write a short snippet of code to break a shapefile up according to a specific attribute.

Here is my code:

from qgis.core import *
import processing
layer = processing.getObject('2012')
#counter is 15 due to limit  R15
counter = 1

# Write the while filter expression and set it
while (counter <= 15):
    selection = layer.getFeatures(QgsFeatureRequest().setFilterExpression('"Group Comp" LIKE  \'R'+str(counter)+'\' '))
    layer.setSelectedFeatures([k.id() for k in selection])

    #Creates layer from selection
    _writer = QgsVectorFileWriter.writeAsVectorFormat(i,r"E:\Scratch\test\NewFile"+str(counter)+".shp","utf-8",None,"ESRI Shapefile", True)
    counter = counter + 1

I get the following error in Qgis when running the above code:

Traceback (most recent call last):
  File "<input>", line 5, in <module>
NameError: name 'i' is not defined

Is my selection of the layer incorrect?

  • 1
    You need to type layer instead of i. However, I'm not sure that the selection is applied in that way... – mgri May 4 '17 at 8:01
  • @mgri - You should post your comment as an answer as the code works perfectly with the selection :) – Joseph May 4 '17 at 9:45
  • @Joseph I was not sure about the using of while statement with that expression: did you run a similar test? – mgri May 4 '17 at 9:48
  • @mgri - Yes, I ran a test with the same field name and values. The output shapefiles were correct with the while loop =) – Joseph May 4 '17 at 9:52
3

You get that error because you haven't defined i as a variable. Instead of i, you should specify the layer on which you are working.

You may try to use this code:

from qgis.core import *
import processing
layer = processing.getObject('2012')
#counter is 15 due to limit  R15
counter = 1

# Write the while filter expression and set it
while (counter <= 15):
    selection = layer.getFeatures(QgsFeatureRequest().setFilterExpression('"Group Comp" LIKE  \'R'+str(counter)+'\' '))
    layer.setSelectedFeatures([k.id() for k in selection])

    #Creates layer from selection
    _writer = QgsVectorFileWriter.writeAsVectorFormat(layer,r"E:\Scratch\test\NewFile"+str(counter)+".shp","utf-8",None,"ESRI Shapefile", True)
    counter = counter + 1

instead of what you have provided (I only changed i with layer).

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.