I have some layers that contain attachments (photos and videos). The layers have the following attributes: ['ATTACHMENTID', 'GLOBALID', 'REL_GLOBALID', 'CONTENT_TYPE', 'ATT_NAME', 'DATA_SIZE', 'DATA'] The attachments are stored in the DATA field. I want to export the attribute table as CSV except the DATA field, as it inflates the field and contains no useful information. I used the following code:

def save_layer_as_csv(layer, save_path, save_name):
    '''Solutions from:https://gis.stackexchange.com/a/373856/95891

    "utf-8",driverName = "CSV" , layerOptions = ['GEOMETRY=AS_XYZ'])

This code exports all the fields which are not needed. I found a good post here that exports only one field of the layer by adding attributes=[idx], onlySelected=True to the line above, but I don't know how to slice the fields as object and add them to the attribute parameter!

I tried to slice using the layer.fields()[:-1] code, but it returned an error argument 1 has unexpected type 'slice'

How can I solve this issue to export all the fields except the last one?

Note: I use QGIS 3.26.2-Buenos Aires

2 Answers 2


You can construct indices' list.

idxs = [layer.fields().indexFromName(f) for f in fields]

And use attributes=idxs instead of attributes=[idx] as parameter.

  • Many thanks for this answer, you made a generalizable answer. However, I would like to add a clarification that I did not know before your answer. the attributes= accepts a list of numbers, not a list of fields object, i.e., my problem could be solved by adding attributes=[0, 1, 2, 3, 4, 5] to the CSV writing statement. Commented Oct 18, 2022 at 20:48

layer.fileds() returns a QgsFields object, not a list. If you need to omit the last field, use this:

idxs = list(range(len(layer.fields())- 1))

And use attributes=idxs.


Your Answer

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

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