2

I just started using PyQGIS and I am not familiar with many of the commands.

In ArcPy, you can use the command arcpy.ListFields to print out the fields present in a shapefile. I'm wondering if there is an equivalent command in PyQGIS?

I am working in Python 3.6 and QGIS 3.0 Girona.

  • In python2.7, you can use layer.getFields(), that will return a QgsFields object. The you can use QgsFields.toList() to iterate over all QgsField. Basically, if you want to get a list of field names use [field.name() for field in layer.getFields().toList()]. But I do not know if this works for QGis 3.0 – xlDias May 16 '18 at 19:54
  • This is more relevant for QGIS 2.X but have you tried what is suggested here? gis.stackexchange.com/questions/76364/… – Trevor J. Smith May 16 '18 at 19:55
5

QgsVectorLayer class has a fields method for it. Using the QGIS Python console you can try this code (the current layer should be a vector layer (instance of QgsVectorLayer)):

>>> layer = iface.activeLayer()
>>> layer
<qgis._core.QgsVectorLayer object at 0x7f5e031ccc18>
>>> layer.fields()
<qgis._core.QgsFields object at 0x7f5e031ccca8>
>>> print (layer.fields()[0])
<qgis._core.QgsField object at 0x7f5e031deca8>
>>> for field in layer.fields():
...    print(field.name(), field.typeName())
name String
id Integer
area Integer64

For further information see https://qgis.org/api/classQgsField.html and https://qgis.org/api/classQgsFields.html

  • Judging from the tags, I think she's trying to do this in an IDE outside of the builtin python console. Other than selecting later via iface, would the steps be the same? – Trevor J. Smith May 18 '18 at 15:16

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.