0

I am new to PyQGIS and I want to add one more field in my existed table. Here is my code:

pointLayer = QgsVectorLayer(uri, 'my_layer', 'delimitedtext')
pointLayer.dataProvider().addAttributes([QgsField("new1", QVariant.Double)])
pointLayer.updateFields()

However, there's no difference if I print the names of the field before and after adding attributes respectively.

enter image description here

I don't know how to fix the problem and the code does not have any error.

1
1

TLDR: you can't if using "delimitedtext" option to open CSV, you can if using "ogr" to open the layer. The 2nd choice restrict what you can do when opening compared to the 1st option and you will be limited by what ogr can do (see driver info behind QGIS scene https://gdal.org/drivers/vector/csv.html#creation-issues). Last option: do not choose CSV to add fields as it can't keep types in columns when you reopen. Choose another format and export to CSV if you really have the requirements

Option 1:

Proof to show you can't edit using "delimitedtext" layer by running below code after selecting your CSV layer:

layer = iface.activeLayer()
cap = layer.dataProvider().capabilities()
if cap & QgsVectorDataProvider.AddAttributes:
    print('Allows addition of new attributes (fields)')
else:
    print('Do not allows addition of new attributes (fields)')

You can also use a version to summarize all capabilities by running

layer = iface.activeLayer()
print(layer.dataProvider().capabilitiesString())

For a shp, it will return Add Features, Delete Features, Change Attribute Values, Add Attributes, Delete Attributes, Rename Attributes, Create Spatial Index, Create Attribute Indexes, Fast Access to Features at ID, Change Geometries

For a delimited txt, it will return Create Spatial Index, Fast Access to Features at ID, Curved Geometries. In 2nd case, as Add Attributes is missing you interpret it's not possible.

You can test other properties related to the provider capabilities using list from https://qgis.org/api/classQgsVectorDataProvider.html#a1a360c9e78933697b9f9be334cfcaf7a

Option 2:

If you really want to edit using ogr, the recipe below works

pointLayer = QgsVectorLayer('/tmp/test1.csv|layername=test1|option:X_POSSIBLE_NAMES=X|option:Y_POSSIBLE_NAMES=Y', 'my_layer', 'ogr')
pointLayer.dataProvider().addAttributes([QgsField("new1", QVariant.Double)])
pointLayer.updateFields()

Content of file test1.csv

point_id,X,Y,ele,time,Ds,len
"371",0.6644, 45.89,486,2020/04/07 09:58:07,0,0
"372",1.2697,44.38,486.2,2020/04/07 09:58:08,8.544,8.54

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.