QGIS version 3.4

I need to copy all selected attributes from the field 'HomePostcode' into the field 'Postcode' through PyQGIS. Using the field calculator I would simply use the expression "HomePostcode", ensuring I'm updating field 'Postcode's selected features only.

enter image description here

I've searched high and low for relatable code and the following is the best I can come up with:

#adds layer to map
uri = 'C:/Users/xxxx/Cleaned.csv'
join_layer = iface.addVectorLayer(uri, 'Cleaned', 'ogr')
target_field = 'Postcode'

def calculate_attributes():
    """Calculates values for 'Postcode' by copying attributes from HomePostcode column and adds them to 'Postcode' column"""

with edit(join_layer):
    for feature in join_layer.getFeatures():
        feature.setAttribute(feature.fieldNameIndex('Postcode'), feature['HomePostcode'])
print(f"Attribute calculated for {target_field} field")


The Python console reads the script but I get a critical error "OGR error syncing to disk: Cannot rename files".

I know the above (if it worked) would just copy all values from HomePostcode to Postcode but I cannot find any clear documentation to target selected features only for QGIS 3.0.

  • 1
    the problem is, that your datasource is a csv file which can not be edited with QGIS
    – eurojam
    Commented Jul 26, 2019 at 16:12
  • You can use a formula or AutoField plugin to accomplish this. Commented Jul 26, 2019 at 17:26

1 Answer 1


Like this to address only the selected features:

fids = join_layer.selectedFeatureIds()
request = QgsFeatureRequest()
with edit(join_layer):
    for feature in join_layer.getFeatures(request):
        feature.setAttribute(feature.fieldNameIndex('Postcode'), feature['HomePostcode'])

Since you cannot edit the .csv directly, you can make a copy to memory, alter that and then export again to .csv. Somewhere in between, there must be a step, where you actually select the features, anyways.

  • superb, thank you very much!
    – James B
    Commented Jul 29, 2019 at 11:13

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.