[GIS] Opening .vrt file with rasterio in Python

gdalpythonrasterio

I have 3 raster files (.tiff files) which are geographically 3 consecutive tiles of a particular area. I am trying to make a .vrt file of 2 out of these 3 files using the gdalbuildvrt python command. The issue I am facing is suppose if I am making a .vrt file (named test.vrt) of the first 2 files (say file 1 & 2) and opening it with rasterio python, it's opening correctly. Subsequently, I want to create a .vrt file of the new file combinations (say file 1 & 3) and overwrite the old .vrt file (test.vrt) with this file combination and try to open it with rasterio python. The problem I am facing now is it's still displaying the the .vrt file with the old file combinations (having files 1 & 2 and not files 1 & 3). The code which I used till now is:

import rasterio 
import rasterio.plot

from osgeo import gdal

vrt_options = gdal.BuildVRTOptions(resampleAlg='cubic', addAlpha=True)
test_vrt = gdal.BuildVRT(r'D:\Test TIFF\test.vrt', [r'D:\Test TIFF\Tile_58_LULC250k_2015_16_revised.tif', r'D:\Test TIFF\Tile_60_LULC250k_2015_16_revised.tif'], options=vrt_options)

test_vrt = None

raster_vrt = rasterio.open(r'D:\Test TIFF\test.vrt')

rasterio.plot.show(raster_vrt)

Also, if I am opening this new .vrt file with QGIS its displaying the correct file combinations (file 1 & 3). So what I understood is the .vrt file has changed after running the gdalbuildvrt command but there is some problem while opening it with rasterio python because it's displaying old .vrt file (file 1 & 2).

Can someone help me figure out what is the problem?

Best Answer

A common idiom is to use a with statement when opening a file so that it is automatically closed when the with block is complete. To adapt the existing answer:

import rasterio 
import rasterio.plot

from osgeo import gdal

vrt_options = gdal.BuildVRTOptions(resampleAlg='cubic', addAlpha=True)
test_vrt = gdal.BuildVRT(r'D:\Test TIFF\test.vrt', [r'D:\Test TIFF\Tile_58_LULC250k_2015_16_revised.tif', r'D:\Test TIFF\Tile_60_LULC250k_2015_16_revised.tif'], options=vrt_options)

test_vrt = None

with rasterio.open(r'D:\Test TIFF\test.vrt') as raster_vrt:

    rasterio.plot.show(raster_vrt)
Related Question