the rasters in that folder has dates in the naming (for eg. T43RGP_20220330T052639_NDVI) and I want the code to read the rasters one by one in the increasing order of the date.

Help me complete this below code on python-

for file in os.listdir(path):
    img = gdal.Open(path_str+"\\"+file)
    img_array = np.array(img.GetRasterBand(1).ReadAsArray())
  • I assume you define path_str somewhere, or did you mean path? Commented Sep 7, 2022 at 12:24

1 Answer 1


Looks like a python problem. You can sort the list by the date like this, but it will only work if the files are named exactly like your example. So the date can be found by splitting at _ and T

import os
from datetime import datetime as dt
path = r'C:\GIS\data'

files = [os.path.join(path, item) for item in os.listdir(path) if 'NDVI' in item and os.path.isfile(os.path.join(path, item))]
#['C:\\GIS\\data\\T43RGP_20220330T052639_NDVI.tif', 'C:\\GIS\\data\\T43RGP_20220101T052639_NDVI.tif', 'C:\\GIS\\data\\T43RGP_20221231T052639_NDVI.tif'] #Not sorted by date

files.sort(key=lambda x: dt.strptime(os.path.basename(x).split('_')[1].split('T')[0], '%Y%m%d')) #Extract the date, convert it to datetime and sort by it
#['C:\\GIS\\data\\T43RGP_20220101T052639_NDVI.tif', 'C:\\GIS\\data\\T43RGP_20220330T052639_NDVI.tif', 'C:\\GIS\\data\\T43RGP_20221231T052639_NDVI.tif'] 

for file in files:
    #Do something
  • 2
    Nice! Please accept my answer with the checkbox
    – Bera
    Commented Sep 8, 2022 at 9:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.