5

I want to create a buffer around a number of features. It is important for me to keep the attributes of the features in the new buffer.shp layer. When I try to write a new VectorLayer with a QgsVectorFileWriter, I do get the buffered polygons and also the fields of the original layer get copied over, however the attribute table stays empty.

How can I copy over the attributes of the original layer to the buffer layer?

As you can see I already tried to load the attributes using the . attributes() method on the QgsFeature object and setting the attributes. However I feel I am missing something here.

for f in feats:
 attributes = f.attributes()
 f.setAttributes(attributes)

See full code below:

path = '/Volumes/VAW_ETH-Z/M.Thesis/data/geospatial/'
# load filtered sgi
sgi_filtered = QgsVectorLayer(path + 'sgi_filtered.shp')
## Create buffer around filtered sgi
outFn = path + 'gl_buffer3.shp'
bufferDist = 50 # in map units
fields = sgi_filtered.fields()
feats = sgi_filtered.getFeatures()
writer = QgsVectorFileWriter(
 outFn,
 'utf-8',
 fields,
 QgsWkbTypes.Polygon,
 sgi_filtered.sourceCrs(), # loads the reference system of the source feature
 'ESRI Shapefile')
for f in feats:
 attributes = f.attributes()
 f.setAttributes(attributes)
 geom = f.geometry()
 buff = geom.buffer(bufferDist, 5)
 f.setGeometry(buff)
 
 writer.addFeature(f)

Screenshot of the Attribute Table below (it shows the fields but no attributes):

Empty Attribute table. The fields are displayed however no attributes have been added.

asked Dec 5, 2022 at 14:16
1

1 Answer 1

5

Just add del writer after for loop.

for f in feats:
 attributes = f.attributes()
 f.setAttributes(attributes)
 geom = f.geometry()
 buff = geom.buffer(bufferDist, 5)
 f.setGeometry(buff)
 
 writer.addFeature(f)
del writer
answered Dec 5, 2022 at 16:17
2
  • Oh thanks a lot! Can you tell me the reason why It is important to delete the writer? Commented Dec 9, 2022 at 14:56
  • You need to delete the writer to flush features to disk. Commented Dec 9, 2022 at 21:43

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.