4

I am trying to add a new column to the attribute table and populate the column with a string, using the python console in QGIS. I have done the same but populating the column with an integer (FIELD_TYPE=1), which works fine, but as soon as I change the column to a string (FIELD_TYPE=2), it no longer works. The code I am trying to run:

out3 = "%s\\roth_vh_%s_3.shp"%(shpPath,year)
processing.runalg('qgis:fieldcalculator',\
out2,\
"polar",\
2,\
4,\
0,\
True,\
'vh',\
out3)

The error message I get is "Evaluation error: Column 'vh' not found". So for some reason it is looking for a column vh rather than taking it as the string to populate all the fields in the column with. It's confusing me though, because if I open the attribute table and run a field calculation to populate a column with a string, I would simply select the column, type the string into the field calculation bar (e.g. 'vh') and click update all, and it would work. Any ideas why the field calculation of 'vh' is not working in pyqgis please?

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Jan 30, 2018 at 12:47

1 Answer 1

4

When you type vh as an expression in the Field Calculator, it assumes you are calling a field. If you type 'vh' (note the single quotes), it treats this as a string value.

In your code, you are doing the former (i.e. calling a field name). What you will need to do is call it as a string instead but be careful when using single quotes to specify a string parameter because you will also need single quotes to speficy the actual value. In which case, you would need to escape it using the following so that it reads 'vh' correctly:

'\'vh\''

So your code could look like:

out3 = "%s\\roth_vh_%s_3.shp"%(shpPath,year)
processing.runalg('qgis:fieldcalculator',\
out2,\
"polar",\
2,\
4,\
0,\
True,\
'\'vh\'',\
out3)

You could also use triple quotes to specify the string parameter and use an expression the same way you would write it in the Field Calculator:

""" 'vh' """,\
answered Jan 30, 2018 at 12:58

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.