Python Rasterio – How to Fix Rasterio Failing to Create New TIFF Inside a For Loop

directorypythonrasterrasterio

I'm trying to save rasters with rasterio inside for loop.
For reason that I don't understand, the for loop works only in the first loop (being able to save the tiff image) but then when comes to the 2nd iteration it fails due to RasterioIOError:

RasterioIOError: Attempt to create new tiff file
'result/imgs/K/K.tiff' failed: No such file or
directory

This is my code:

loc_raster='result/imgs/'
for shape in shapes:
    #extract the name of the raster
    test_name = re.search(r'/(.*?)-', shape).group(1)
    element=test_name.split('/')[2]
........do things.................................
    raster_name=element+'/'+element+'.tiff'


    savedir = pathlib.Path(loc_raster)
    #create the dir, including nested dirs and don't complain if it is already there
    savedir.mkdir(parents=True,exist_ok=True)    
    
    #get crs as wkt
    from rasterio.crs import CRS

    rasterCrs = CRS.from_epsg(4326)
    rasterCrs.data
    {'init': 'epsg:4326'}

    #definition, register and close of interpolated raster
    triInterpRaster = rasterio.open(savedir/raster_name,
                                    'w',
                                    driver='GTiff',
                                    height=bbox_size[1],
                                    width=bbox_size[0],
                                    count=1,
                                    dtype=field.dtype,
                                    crs={'init': 'epsg:4326'},
                                    transform=transf,
                                    )
    triInterpRaster.write(field,1)
    triInterpRaster.close()    

That works and saves the first raster in the correct folder, but then in the 2nd iteration, when the raster name is K I get the following error:

RasterioIOError: Attempt to create new tiff file
'kriging_result/group1/imgs/K/K.tiff' failed: No such file or
directory

I don't know what is the reason for this as it seems to be the right directory, so I can't understand why is this happen. Maybe is becase it's only one letter, K?

My end goal is to be able to save the images in the following iterations after the first.

Best Answer

I think your issue is this: raster_name = element+'/'+element+'.tiff'. You are not creating the folder element in your mkdir() call, so when trying to save, the folder K exists but not the second folder K inside that folder.