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?

4
  • 1
    You need to type layer instead of i. However, I'm not sure that the selection is applied in that way... Commented May 4, 2017 at 8:01
  • @mgri - You should post your comment as an answer as the code works perfectly with the selection :) Commented May 4, 2017 at 9:45
  • @Joseph I was not sure about the using of while statement with that expression: did you run a similar test? Commented May 4, 2017 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 =) Commented May 4, 2017 at 9:52

1 Answer 1

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 and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.