0

I am new to GDAL in Python (and Python in general), so as a way to begin learning, I am trying to perform basic functions such as getting extents from a single raster and printing them out.

However, I'm having some issues opening a file using gdal.Open. I believe I have the syntax correct, and Visual Studio Code does not throw any errors, but I am not able to print out the desired information.

import os
from osgeo import gdal
file = "tile1.tif"
ds = gdal.Open(file)
ulx, xres, xskew, uly, yskew, yres = ds.GetGeoTransform()
lrx = ulx + (ds.RasterXSize * xres)
lry = uly + (ds.RasterYSize * yres)
print (lrx ',' lry)
  • print (lrx ',' lry) should raise a SyntaxError as it's invalid python. Did you mean print (lrx, lry)? – user2856 Feb 11 at 5:32
2

Running your code it drops an error message on the print function:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'float' and 'str'

You try to add float and string variables which is not possible in Python. Change your last line to this:

"{:.3f}, {:.3f}".format(lrx, lry)

if you would like three decimals in the result or this

"{}, {}".format(lrx, lry)

to let Python set the precision of the output.

  • Hi Zoltan, When I posted the question, I had print (lrx + ',' + lry) at the suggestion of a friend, but I actually just want to print both values side by side. I don't want to add anything and I think they might have misunderstood. I just want to display the resulting values. I have edited the question. Thanks. – wyatt8919 Feb 10 at 19:03
  • My answer just do this. Print the two values side by side. – Zoltan Feb 10 at 19:06
  • I do not understand what you mean...I am now using print"{:.3f}, {:.3f}".format(lrx, lry) and it is throwing an error. – wyatt8919 Feb 10 at 19:21
  • Oh wait, yet another syntax issue on my end. I implemented your fix and it worked. However, can you explain why this works? Or point me to a good article? Which are floats and which are variables? Thanks. – wyatt8919 Feb 10 at 19:26
  • 1
    Variables in your code are file, ds, ulx, xres, xskew, uly, yskew, yres, lrx, lry which have data type. For example file has type string, ulx, xres, xskew, uly, yskew, yres, lrx, lry have type float (number with decimals). I suppose you should start a Python book for beginners. This book may help: greenteapress.com/thinkpython/thinkpython.pdf – Zoltan Feb 10 at 19:45

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.