I have a folder with filenames bio1_36.tif, bio1_37.tif, bio2_36_tif, bio2_37.tif, and so on. There are 19 bio variables and 36 and 37 at the end refer to the tile numbers. My goal is to mosaic the two tiles for each variable, clip to the size of a polygon layer called “Katanga” and convert the final output to asci format. I’ve been using the code below however this will only generate the correct output if the two tiles for the same bio variable are specified in the code or these two files are the only input in the workspace folder.

How can I do the above procedure in a recursive manner for each bio variable, i.e. setting up a loop?

This way I don’t have to create separate folders for each bio variable or specify them in the code.

I am new to Python.

Below is the code I’ve been using (note: "test" folder only contains one bio variable with the two tiles):

import arcpy
from arcpy import env
from arcpy.sa import*
import time

start_time = time.clock()
env.workspace = "G:/Eck_health_disease/spatial data/WorldClimate data/test"
arcpy.env.overwriteOutput = True
ImgList = arcpy.ListRasters()
print "Processing Mosaic"
print "Number of tiles to be Mosaicked:" + str(len(ImgList))
arcpy.MosaicToNewRaster_management(ImgList, env.workspace, "bio1_mos.tif",    pixel_type="32_BIT_FLOAT", cellsize="", number_of_bands="1", mosaic_method="", mosaic_colormap_mode="MATCH")
Katanga_poly = "G:/Eck_health_disease/spatial data/COD_adm_shp/DRC_Katanga.shp"
arcpy.Clip_management("bio1_mos.tif","21.7447528839 -13.4556760785 30.7780862172 -4.99734274513", "bio1_mos_Kat.tif", Katanga_poly, "#", "ClippingGeometry", "MAINTAIN_EXTENT")
arcpy.RasterToASCII_conversion("bio1_mos_Kat.tif", "bio1_mos_Kat.asc")
print "Task Completed!"
print time.clock() - start_time, "seconds"

1 Answer 1


Use some of python's standard string formatting functions and create a unique list (set) of your base file names. Then you can iterate the set object and run your processing steps for each bio value.

This code should get you started

ImgList = arcpy.ListRasters()

bio_list = []
for ras in ImgList:
    a = ras.split('_')
    b = '_'.join(a[:-1])
bio_set = set(bio_list)

for x in bio_set:
    ras1 = x + '_36.tif'
    ras2 = x + '_37.tif'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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