Personally, I prefer to use the changeAttributeValues()
method of QgsVectorDataProvider
(see API docs here) as I find it more reliable. This method takes an attributes map which is basically a dictionary where the key is a feature id and the value is a second dictionary comprising field indexes as keys and the new attributes as values. Try
I have tested this starting with a csv file with the following structure:
After running the following code below:
srcFile = "D'D:\\Data\\filename.csv"
csv'
layer = QgsVectorLayer("Polygon?crs=EPSG:2193", "Polygons", "memory")
QgsProject.instance().addMapLayer(layer)
provider = layer.dataProvider()
provider.addAttributes([QgsField('ViewName',QVariant.String, '', 50, 0),
QgsField('FigName',QVariant.String, '', 10, 0)])
layer.updateFields()
f1 = layer.fields().lookupField('ViewName')
f2 = layer.fields().lookupField('FigName')
fid = 1
with open(srcFile,'r') as infile:
rectcsv_lines = infile.readlines()[1:]
for bline in rect[1:]csv_lines:
partsline = bline.split(',')
#### Coordinates coming from CSV ####
xMin = float(parts[2]line[2])
yMin = float(parts[3]line[3])
xMax = float(parts[4]line[4])
yMax = float(parts[5]line[5])
rect = QgsRectangle(xMin, yMin, xMax, yMax)
polygon = QgsGeometry.fromRect(rect)
feature = QgsFeature()
feature.setGeometry(polygon)
with edit(layer):
provider.addFeatures([feature])
provider.changeAttributeValues({feature.id():atts = {f1: parts[0]line[0], f2: parts[line[-2]}
provider.changeAttributeValues({fid: atts})
fid += 1
The resulting layer and attribute table looks like this: