I'm writing a script that will iterate rasters and do some calculations on each raster. I would like the formula in the GDAL raster calculator to include a variable, which I read from a txt file. I don't want the user to insert the variable but to integrate it in the script.

The code of the raster calculator I use is this:

outputs_GDALOGRRASTERCALCULATOR_1=processing.runalg('gdalogr:rastercalculator', rlayer,'1',None,'1',None,'1',None,'1',None,'1',None,'1','10000*(A*0.00002-0.1)/sin(65)*(A>0.001)','0',4,None,outputName)

I need the number inside of the sin, in this example 65, to be a variable, so every time I'll have a different number.

Is that possible to integrate a variable in this syntax?


You could use Python's .format() method to include reading a variable from a textfile. The following is a simple example of reading each line in a text file and then running the raster calculator on rlayer for each variable. This is assuming your text file looks like this:



f = open('path/to/file.txt')
lines = f.read().splitlines()
for line in lines:
    outputs_GDALOGRRASTERCALCULATOR_1=processing.runalg('gdalogr:rastercalculator', rlayer,'1',None,'1',None,'1',None,'1',None,'1',None,'1','10000*(A*0.00002-0.1)/sin({})*(A>0.001)'.format(line),'0',4,None,outputName)
  • 1
    Thank you very much, it helped. Now I understand that the formula for calculation is actually a string and not numbers, so it is possible to create the desired string beforehand and then just add the string variable instead of the entire formula. Like that: syntax = '(A>0.001)*10000*(A*0.00002-0.1)/sin('+str(SUN_ELEVATION)+') outputs_GDALOGRRASTERCALCULATOR_1=processing.runalg('gdalogr:rastercalculator', rlayer,'1',None,'1',None,'1',None,'1',None,'1',None,'1',syntax,'0',4,None,outputName) – user88484 Feb 8 '17 at 8:37
  • @user88484 - Most welcome, glad it helped! And very nicely done :) – Joseph Feb 8 '17 at 10:40

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.