'How to prevent GDAL from writing data source to disk when de-referenced

I need to extract the raster (stored as a numpy array) from a file. Following the very popular OGR Cookbook, I am reading in an OGR layer (geojson) and then rasterizing the vectors. I read that array using GDAL's ReadAsArray() function. That all works fine, and I can do all sorts of numpy things to it. However, GDAL automatically writes out the GDAL dataset I create because its automatically de-referenced once the program ends. I don't need/want this file to be output because its useless to have on disk, I just need the data in memory. How can you prevent this from happening?

I've tried not calling the FlushCache() function, but the file still gets output in the end. Code:

...

    # Create the destination data source
    target = gdal.GetDriverByName('GTiff').Create(output_raster_path, source_raster.RasterXSize, source_raster.RasterYSize, 1, gdal.GDT_UInt16)
    target.SetGeoTransform(source_raster.GetGeoTransform())
    target.SetProjection(source_raster.GetProjection())
    band = target.GetRasterBand(1)
    band.SetNoDataValue(no_data_value)
    gdal.RasterizeLayer(target, [1], source_layer, options=["ATTRIBUTE=BuildingID"])
    raster = band.ReadAsArray()
    return raster

Afterwards, once the program completes, a geotiff is written to output_raster_path, which I had just set as "temp.tif".



Solution 1:[1]

You can use In-Memory Driver for things like that.

mem_drv = gdal.GetDriverByName('MEM')
target = mem_drv.Create('', source_raster.RasterXSize, source_raster.RasterYSize, 1, gdal.GDT_UInt16)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kmuehlbauer