2

I get the error: AttributeError: 'NoneType' object has no attribute 'selectByExpression'

The first run through the loop is fine but at the second run the error occurs.

How do I fix this?

import processing
import os
import shutil
import time

t_begin = time.localtime()
print(time.strftime('%H:%M:%S', t_begin))

input = 'C:/Users/laptop Innoforte 1/Innoforte/Innoforte Druten - Documenten/1. projecten/2. status uitvoering/GOV duurzame energiesystemen/3. rekenmodellen/QGIS/PDots.shp'
N=0


while(N<10):
    print("N="+str(N))
    outFile = 'C:/Users/laptop Innoforte 1/Innoforte/Innoforte Druten - Documenten/1. projecten/2. status uitvoering/GOV duurzame energiesystemen/3. rekenmodellen/QGIS/QGIS template/temp_buffer'+str(N)+'.shp'
    layer = iface.addVectorLayer(input,'','ogr')
   # geselecteerd1 = layer.selectByExpression("kleur = 'blue'")
    geselecteerd1= layer.selectByExpression("kleur = 'blue'")
    #puntlaag voor buffer maken########################################################
    BufferFile = 'C:/Users/laptop Innoforte 1/Innoforte/Innoforte Druten - Documenten/1. projecten/2. status uitvoering/GOV duurzame energiesystemen/3. rekenmodellen/QGIS/QGIS template/buffer'+str(N)+'.shp'
    #print(BufferFile)

    writer = QgsVectorFileWriter.writeAsVectorFormat(layer,BufferFile,'utf-8',
    driverName = 'ESRI Shapefile', onlySelected= True)

    #selected_layer1 = iface.addVectorLayer(BufferFile,'','ogr')
    del(writer)

    #buffer maken met puntlaag "BufferFile"###########################################
    processing.run("native:buffer", {'INPUT':'C:/Users/laptop Innoforte 1/Innoforte/Innoforte Druten - Documenten/1. projecten/2. status uitvoering/GOV duurzame energiesystemen/3. rekenmodellen/QGIS/QGIS template/buffer'+str(N)+'.shp',
    'DISTANCE':30,'SEGMENTS':5,'END_CAP_STYLE':0,'JOIN_STYLE':0,
    'MITER_LIMIT':2,'DISSOLVE':False,
    'OUTPUT':outFile})

    #iface.addVectorLayer(outFile,'','ogr') #voeg bufferlaag toe aan kaart

    layer.removeSelection()
    geselecteerd2 = layer.selectByExpression("kleur = 'red'")

    #puntlaag maken van rode punten####################################################
    RedDots = 'C:/Users/laptop Innoforte 1/Innoforte/Innoforte Druten - Documenten/1. projecten/2. status uitvoering/GOV duurzame energiesystemen/3. rekenmodellen/QGIS/QGIS template/RedDots'+str(N)+'.shp'
    writer = QgsVectorFileWriter.writeAsVectorFormat(layer,RedDots,'utf-8',
    driverName = 'ESRI Shapefile', onlySelected= True)

    #selected_layer2 = iface.addVectorLayer(RedDots,'','ogr')
    del(writer)

    #layer.removeSelection()

    #rode punten in buffer tellen#######################################################
    CountFile = "C:/Users/laptop Innoforte 1/Innoforte/Innoforte Druten - Documenten/1. projecten/2. status uitvoering/GOV duurzame energiesystemen/3. rekenmodellen/QGIS/QGIS template/temp_count"+str(N)+".shp"
    if (N==2):
        processing.run("native:createspatialindex", {'INPUT':RedDots})
    else:
        processing.run("native:createspatialindex", {'INPUT':RedDots})

    processing.run("native:countpointsinpolygon",{
    'POLYGONS':outFile,
    'POINTS':RedDots,
    'WEIGHT':'','CLASSFIELD':'','FIELD':'NUMPOINTS2',
    'OUTPUT':CountFile})

    #iface.addVectorLayer(CountFile,'','ogr')

    #punten maken van polygoon punten tellen################################################
    NewDots = "C:/Users/laptop Innoforte 1/Innoforte/Innoforte Druten - Documenten/1. projecten/2. status uitvoering/GOV duurzame energiesystemen/3. rekenmodellen/QGIS/QGIS template/NewDots"+str(N)+".shp"
    processing.run("native:centroids", 
    {'INPUT': CountFile,'ALL_PARTS':True,'OUTPUT':NewDots})

    iface.addVectorLayer(NewDots,'','ogr')

    # blauw naar rood maken###############################################################
    layer = iface.activeLayer()

    layer.startEditing()

    for feature in layer.getFeatures():
        if feature ['NUMPOINTS2'] ==0:
            layer.changeAttributeValue(feature.id(), layer.fields().indexFromName('kleur'),'blue')
        else:
           layer.changeAttributeValue(feature.id(), layer.fields().indexFromName('kleur'),'red') 
    layer.commitChanges()



    # rood en blauw samenvoegen##################################################################
    CombineDots = "C:/Users/laptop Innoforte 1/Innoforte/Innoforte Druten - Documenten/1. projecten/2. status uitvoering/GOV duurzame energiesystemen/3. rekenmodellen/QGIS/QGIS template/CombineDots"+str(N)+".shp"

    processing.run("native:mergevectorlayers", 
    {'LAYERS': [NewDots,RedDots],'CRS':None,'OUTPUT':CombineDots})

    iface.addVectorLayer(CombineDots,'','ogr')

    #kleur aanpassen##################################################################3
    layer = iface.activeLayer()

    # define some rules: label, expression, color name, (min scale, max scale)
    road_rules = (
        ('rood', "kleur ='red'", 'red', None),
        ('blauw', "kleur ='blue'",'blue', None)
    )

    # create a new rule-based renderer
    symbol = QgsSymbol.defaultSymbol(layer.geometryType())
    renderer = QgsRuleBasedRenderer(symbol)

    # get the "root" rule
    root_rule = renderer.rootRule()

    for label, expression, color_name, scale in road_rules:
        # create a clone (i.e. a copy) of the default rule
        rule = root_rule.children()[0].clone()
        # set the label, expression and color
        rule.setLabel(label)
        rule.setFilterExpression(expression)
        rule.symbol().setColor(QColor(color_name))
        # set the scale limits if they have been specified
        if scale is not None:
            rule.setScaleMinDenom(scale[0])
            rule.setScaleMaxDenom(scale[1])
        # append the rule to the list of rules
        root_rule.appendChild(rule)

    # delete the default rule
    root_rule.removeChildAt(0)

    # apply the renderer to the layer
    layer.setRenderer(renderer)


    #laag verwijderen#########################################################################
    TempLayer1 = QgsProject.instance().mapLayersByName('NewDots'+str(N))[0].id()
    if (N==0):
        TempLayer2 = QgsProject.instance().mapLayersByName('PDots')[0].id()
    else:
        None
        ### vorige verwijderen############ 
        #Templayer3=QgsProject.instance().mapLayersByName('CombineDots'+str(N))[0].id()
        #QgsProject.instance().removeMapLayers([TempLayer3])
    
    
    QgsProject.instance().removeMapLayers( [TempLayer1] )
    #QgsProject.instance().removeMapLayers( [TempLayer2] )
   
    
#############################################################################################
    N =N+ 1
    
    input = "C:/Users/laptop Innoforte 1/Innoforte/Innoforte Druten - Documenten/1. projecten/2. status uitvoering/GOV duurzame energiesystemen/3. rekenmodellen/QGIS/QGIS template/CombineDots"+str(N)+".shp"
    
else:
    print(str(N)+"x doorlopen")
i=0
while (i<(N-1)):
    TempLayerX = QgsProject.instance().mapLayersByName('CombineDots'+str(i))[0].id()
    QgsProject.instance().removeMapLayers( [TempLayerX] )
    TempLayerX = QgsProject.instance().mapLayersByName('CombineDots'+str(i))[0].id()
    QgsProject.instance().removeMapLayers( [TempLayerX] )
    i = i+1
else:
    t_eind = time.localtime()
    print(time.strftime('%H:%M:%S', t_eind))



import processing
import os
import shutil
import time

t_begin = time.localtime()
print(time.strftime('%H:%M:%S', t_begin))

input = 'C:/Users/laptop Innoforte 1/Innoforte/Innoforte Druten - Documenten/1. projecten/2. status uitvoering/GOV duurzame energiesystemen/3. rekenmodellen/QGIS/PDots.shp'
N=0


while(N<10):
    print("N="+str(N))
    outFile = 'C:/Users/laptop Innoforte 1/Innoforte/Innoforte Druten - Documenten/1. projecten/2. status uitvoering/GOV duurzame energiesystemen/3. rekenmodellen/QGIS/QGIS template/temp_buffer'+str(N)+'.shp'
    layer = iface.addVectorLayer(input,'','ogr')
   # geselecteerd1 = layer.selectByExpression("kleur = 'blue'")
    geselecteerd1= layer.selectByExpression("kleur = 'blue'")
    #puntlaag voor buffer maken########################################################
    BufferFile = 'C:/Users/laptop Innoforte 1/Innoforte/Innoforte Druten - Documenten/1. projecten/2. status uitvoering/GOV duurzame energiesystemen/3. rekenmodellen/QGIS/QGIS template/buffer'+str(N)+'.shp'
    #print(BufferFile)

    writer = QgsVectorFileWriter.writeAsVectorFormat(layer,BufferFile,'utf-8',
    driverName = 'ESRI Shapefile', onlySelected= True)

    #selected_layer1 = iface.addVectorLayer(BufferFile,'','ogr')
    del(writer)

    #buffer maken met puntlaag "BufferFile"###########################################
    processing.run("native:buffer", {'INPUT':'C:/Users/laptop Innoforte 1/Innoforte/Innoforte Druten - Documenten/1. projecten/2. status uitvoering/GOV duurzame energiesystemen/3. rekenmodellen/QGIS/QGIS template/buffer'+str(N)+'.shp',
    'DISTANCE':30,'SEGMENTS':5,'END_CAP_STYLE':0,'JOIN_STYLE':0,
    'MITER_LIMIT':2,'DISSOLVE':False,
    'OUTPUT':outFile})

    #iface.addVectorLayer(outFile,'','ogr') #voeg bufferlaag toe aan kaart

    layer.removeSelection()
    geselecteerd2 = layer.selectByExpression("kleur = 'red'")

    #puntlaag maken van rode punten####################################################
    RedDots = 'C:/Users/laptop Innoforte 1/Innoforte/Innoforte Druten - Documenten/1. projecten/2. status uitvoering/GOV duurzame energiesystemen/3. rekenmodellen/QGIS/QGIS template/RedDots'+str(N)+'.shp'
    writer = QgsVectorFileWriter.writeAsVectorFormat(layer,RedDots,'utf-8',
    driverName = 'ESRI Shapefile', onlySelected= True)

    #selected_layer2 = iface.addVectorLayer(RedDots,'','ogr')
    del(writer)

    #layer.removeSelection()

    #rode punten in buffer tellen#######################################################
    CountFile = "C:/Users/laptop Innoforte 1/Innoforte/Innoforte Druten - Documenten/1. projecten/2. status uitvoering/GOV duurzame energiesystemen/3. rekenmodellen/QGIS/QGIS template/temp_count"+str(N)+".shp"
    if (N==2):
        processing.run("native:createspatialindex", {'INPUT':RedDots})
    else:
        processing.run("native:createspatialindex", {'INPUT':RedDots})

    processing.run("native:countpointsinpolygon",{
    'POLYGONS':outFile,
    'POINTS':RedDots,
    'WEIGHT':'','CLASSFIELD':'','FIELD':'NUMPOINTS2',
    'OUTPUT':CountFile})

    #iface.addVectorLayer(CountFile,'','ogr')

    #punten maken van polygoon punten tellen################################################
    NewDots = "C:/Users/laptop Innoforte 1/Innoforte/Innoforte Druten - Documenten/1. projecten/2. status uitvoering/GOV duurzame energiesystemen/3. rekenmodellen/QGIS/QGIS template/NewDots"+str(N)+".shp"
    processing.run("native:centroids", 
    {'INPUT': CountFile,'ALL_PARTS':True,'OUTPUT':NewDots})

    iface.addVectorLayer(NewDots,'','ogr')

    # blauw naar rood maken###############################################################
    layer = iface.activeLayer()

    layer.startEditing()

    for feature in layer.getFeatures():
        if feature ['NUMPOINTS2'] ==0:
            layer.changeAttributeValue(feature.id(), layer.fields().indexFromName('kleur'),'blue')
        else:
           layer.changeAttributeValue(feature.id(), layer.fields().indexFromName('kleur'),'red') 
    layer.commitChanges()



    # rood en blauw samenvoegen##################################################################
    CombineDots = "C:/Users/laptop Innoforte 1/Innoforte/Innoforte Druten - Documenten/1. projecten/2. status uitvoering/GOV duurzame energiesystemen/3. rekenmodellen/QGIS/QGIS template/CombineDots"+str(N)+".shp"

    processing.run("native:mergevectorlayers", 
    {'LAYERS': [NewDots,RedDots],'CRS':None,'OUTPUT':CombineDots})

    iface.addVectorLayer(CombineDots,'','ogr')

    #kleur aanpassen##################################################################3
    layer = iface.activeLayer()

    # define some rules: label, expression, color name, (min scale, max scale)
    road_rules = (
        ('rood', "kleur ='red'", 'red', None),
        ('blauw', "kleur ='blue'",'blue', None)
    )

    # create a new rule-based renderer
    symbol = QgsSymbol.defaultSymbol(layer.geometryType())
    renderer = QgsRuleBasedRenderer(symbol)

    # get the "root" rule
    root_rule = renderer.rootRule()

    for label, expression, color_name, scale in road_rules:
        # create a clone (i.e. a copy) of the default rule
        rule = root_rule.children()[0].clone()
        # set the label, expression and color
        rule.setLabel(label)
        rule.setFilterExpression(expression)
        rule.symbol().setColor(QColor(color_name))
        # set the scale limits if they have been specified
        if scale is not None:
            rule.setScaleMinDenom(scale[0])
            rule.setScaleMaxDenom(scale[1])
        # append the rule to the list of rules
        root_rule.appendChild(rule)

    # delete the default rule
    root_rule.removeChildAt(0)

    # apply the renderer to the layer
    layer.setRenderer(renderer)


    #laag verwijderen#########################################################################
    TempLayer1 = QgsProject.instance().mapLayersByName('NewDots'+str(N))[0].id()
    if (N==0):
        TempLayer2 = QgsProject.instance().mapLayersByName('PDots')[0].id()
    else:
        None
        ### vorige verwijderen############ 
        #Templayer3=QgsProject.instance().mapLayersByName('CombineDots'+str(N))[0].id()
        #QgsProject.instance().removeMapLayers([TempLayer3])
    
    
    QgsProject.instance().removeMapLayers( [TempLayer1] )
    #QgsProject.instance().removeMapLayers( [TempLayer2] )
   
    
#############################################################################################
    N =N+ 1
    
    input = "C:/Users/laptop Innoforte 1/Innoforte/Innoforte Druten - Documenten/1. projecten/2. status uitvoering/GOV duurzame energiesystemen/3. rekenmodellen/QGIS/QGIS template/CombineDots"+str(N)+".shp"
    
else:
    print(str(N)+"x doorlopen")
i=0
while (i<(N-1)):
    TempLayerX = QgsProject.instance().mapLayersByName('CombineDots'+str(i))[0].id()
    QgsProject.instance().removeMapLayers( [TempLayerX] )
    TempLayerX = QgsProject.instance().mapLayersByName('CombineDots'+str(i))[0].id()
    QgsProject.instance().removeMapLayers( [TempLayerX] )
    i = i+1
else:
    t_eind = time.localtime()
    print(time.strftime('%H:%M:%S', t_eind))
1
  • 4
    Please Edit the Question to show where the error message is generated.
    – Vince
    Aug 10, 2022 at 12:58

1 Answer 1

3

You must increase variable N after assigning a value to variable input. Because the assigned value of input contains N. If you increase N before input line, you assign a non-existent file to variable input.

Replace two lines below:

From

N = N + 1

input = "C:/Users/laptop Innoforte 1/Innoforte/Innoforte Druten - Documenten/1. projecten/2. status uitvoering/GOV duurzame energiesystemen/3. rekenmodellen/QGIS/QGIS template/CombineDots"+str(N)+".shp"

To

input = "C:/Users/laptop Innoforte 1/Innoforte/Innoforte Druten - Documenten/1. projecten/2. status uitvoering/GOV duurzame energiesystemen/3. rekenmodellen/QGIS/QGIS template/CombineDots"+str(N)+".shp"

N = N + 1
1
  • thank you. I thought it had something to do with the order of lines Aug 11, 2022 at 7:21

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.