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() 
Rahul Verma
  • 181
  • 1
  • 9
  • 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 00: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 00:37

1 Answers1

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...
user2856
  • 65,736
  • 6
  • 115
  • 196
  • 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 01: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 '23 at 09:08