1

I have made an attempt to create a buffer around some points useing PyQGIS. However, when running the following code (see below) I receive and IndexError saying that 'list is out of range'.

What might be the issue?

layerName = "C:/Users/Anna Nilsson/Desktop/AIRPOLIM-ES/GIS data/Kenya/cpp_KE_meters.gpkg"
iface.addVectorLayer(layerName,"coal plants","ogr")
outFn = "C:/Users/Anna Nilsson/Desktop/buffer1.shp"
bufferDist = 100000 #in map units

layers = QgsProject.instance().mapLayersByName(layerName)
layers = layers[0] #buffered layer is the first layer in layers list

fields = layers.fields()
feats = layers.getFeatures()

writer = QgsVectorFileWriter(outFn,'UTF-8',fields,QgsWkbTypes.Point,layers.sourceCrs(),'ESRI Shapefile')

for feat in feats: 
    geom = feat.geometry()
    buff = geom.buffer(bufferDist,5)
    feat.setGeometry(buff)
    writer.addFeature(feat)

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

del(writer)

Error message:

Traceback (most recent call last):
  File "C:\PROGRA~1\QGIS3~1.4\apps\Python37\lib\code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "<string>", line 19, in <module>
IndexError: list index out of range

  • Can you post the full error message. – HeikkiVesanto Jul 17 at 13:00
  • Apologies, of course. Please find below: ``` Traceback (most recent call last): File "C:\PROGRA~1\QGIS3~1.4\apps\Python37\lib\code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 1, in <module> File "<string>", line 19, in <module> IndexError: list index out of range ``` – A.N Jul 17 at 13:04
  • 1
    please use the edit link to update your question – Ian Turton Jul 17 at 13:05
2

try using the layer name instead of its path

layers = QgsProject.instance().mapLayersByName("coal plants")

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.