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() 
2
  • 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 Dec 21, 2018 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. Dec 21, 2018 at 0:37

1 Answer 1

3

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...
2
  • 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 Dec 21, 2018 at 1:11
  • The etc... in my code snippet represents the rest of your code, including the output. I didn't forget it, I deliberately didn't include it as it's not relevant to the question and to keep my answer simple.
    – user2856
    Jan 20 at 9:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.