IF-statement applied to substring of a string in a specific position

Question:

I am working with a bunch of *.tif files which are named like: [20120101.tif, 20120102.tif, 20120103.tif, ...] (i.e. YEARMONTHDAY.tif). The issue is that I have to work only with the files corresponding to some specific months (e.g. JAN, FEB, MAR, NOV, DEC). I was planning to use IF statement but I am not sure how to apply it in order to work only for some months. Bellow, I show my code.

Root_dir = r"f:myTifFiles"
os.chdir(Root_dir)
List_tif = glob.glob("*.tif")

for i in range(len(List_tif)):
    if ... #in this line I was planning to call a conditional statement to work only with some specific months
        Raster = gdal.Open(List_tif[i])
        geotransform = Raster.GetGeoTransform()

I will appreciate any help

Asked By: haitama89

||

Answers:

List_tif = glob.glob("*.tif")
months_to_process = ['01','02','11']  # months you have to work with.

for image in List_tif:
    # extract a substring at index 4,5 example: 20220123.tif ==> 01
    # then check if the extracted value is in the months you need to process.
    # Then you can do what you need
    if image[4:6] in months_to_process:
        Raster = gdal.Open(List_tif[i])
        geotransform = Raster.GetGeoTransform()
Answered By: Nesi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.