Lerchengott
Lerchengott

Reputation: 13

Python - Write Raster with gdal

I want to write a raster with gdal within a function.

def WriteRaster(InputArray, OutputFile, NROWS, NCOLS, XULCorner, YULCorner, Cellsize, wkt_projection):
driver = gdal.GetDriverByName("GTiff")
dataset = driver.Create("%s", NROWS, NCOLS, 1, gdal.GDT_Float32 %(OutputFile))
dataset.SetGeoTransform((XULCorner,Cellsize,0,YULCorner,0,-Cellsize))
dataset.SetProjection(wkt_projection)
dataset.GetRasterBand(1).WriteArray(InputArray)
dataset.FlushCache()
return None

I get this error:

unsupported operand type(s) for %: 'int' and 'str'

I thought I could define the output filename this way. Why not?

Thanks for helping!!!

Upvotes: 1

Views: 3040

Answers (1)

I think that line:

dataset = driver.Create("%s", NROWS, NCOLS, 1, gdal.GDT_Float32 %(OutputFile))

should be something more like:

dataset = driver.Create("%s"%(OutputFile), NROWS, NCOLS, 1, gdal.GDT_Float32 )

see I moved the %(OutputFile) bit?

Although, if OutputFIle is a string, you could use:

dataset = driver.Create(OutputFile, NROWS, NCOLS, 1, gdal.GDT_Float32 )

See https://pyformat.info/ for some more info about format strings.

Upvotes: 1

Related Questions