1

Remember i am using Python Version 3.6.2 QGIS Version 3.2

while running my code i am getting this error:

fields = selectedLayer.pendingFields()
AttributeError: 'QgsRasterLayer' object has no attribute 'pendingFields

if i am using fields() instead of pendingFields() because of qgis version 3x

getting this error:

fields = selectedLayer.fields()
AttributeError: 'QgsRasterLayer' object has no attribute 'fields

i am new in this field so please tell me properly what should i do

here is my code:

    filename = self.dlg.lineEdit.text()
    output_file = open(filename, 'w')

    selectedLayerIndex = self.dlg.comboBox.currentIndex()
    selectedLayer = layers[selectedLayerIndex]
    fields = selectedLayer.pendingFields()
    fieldnames = [field.name() for field in fields]

    for f in selectedLayer.getFeatures():
        line = ','.join(unicode(f[x]) for x in fieldnames) + '\n'
        unicode_line = line.encode('utf-8')
        output_file.write(unicode_line)
    output_file.close() 
  • i just simply created a plugin it didn't ask for QgsRasterLayer or QgsVectorLayer. from qt creator i design my plugin to take the layers raster or vector from my local system and it save output file but when ever i am saving output file i am getting this error – Rahul Verma Dec 21 '18 at 0:35
  • i am absolute beginners in QGIS so i am not getting it well what i want to do is ----- i created my plugin i just want to add some code in my mainPlugin.py file like print('hello') and want to run this in qgis so what should i do. – Rahul Verma Dec 21 '18 at 0:37
2

Your code will not work with raster layers as they have neither fields (QGIS doesn't support raster attribute tables - link) nor features.

fields (pendingFields in 2x) and getFeatures are methods of the QgsVectorLayer class.

So test if your layer has a fields method (i.e if hasattr(selectedLayer, 'fields'): etc... and ignore it if it doesn't. i.e

filename = self.dlg.lineEdit.text()
selectedLayerIndex = self.dlg.comboBox.currentIndex()
selectedLayer = layers[selectedLayerIndex]
if hasattr(selectedLayer, 'fields'):

    fields = selectedLayer.pendingFields()
    fieldnames = [field.name() for field in fields]

    for f in selectedLayer.getFeatures():
        etc...
  • error gone but its not saving my output file. will you forgot to add output_file = open(filename, 'w') in second line. After adding it on 2nd line output file showing in my system – Rahul Verma Dec 21 '18 at 1:11

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.