I have a text file which has the details of many .tif files which have to be converted to a single merged .vrt file in QGIS Python Console.
text = "W:/04 Tools/07 MapMaker/workingfiles/text.txt"
with open(text, 'r') as f:
list_text = [line.strip() for line in f]
list_no = len(list_text)
I created a list called list_text which contains all the .tif files.
vrtSublist = []
for sllist in range(0,list_no):
output_vrt = "W:/04 Tools/07 MapMaker/workingfiles/tif" + "_tile" + str(sllist) + ".vrt"
if os.path.isfile(list_text[sllist]):
general.runalg("gdalogr:buildvirtualraster",list_text[sllist],0,False,False,output_vrt, progress=None)
vrtSublist.append(str(output_vrt))
else:
print ("The file " + list_text[sllist] + " is Not Found. Please add this file.")
So, all the .vrt files are now in vrtSublist. Now, I want to merge 7 .vrt files each into a single .vrt file; so that I will group all the .vrt files in another list called as sublists (where sublists[0] = 7, sublists[1] = 7,…. ).
y_count = 7
sublists = [vrtSublist[x:x+y_count] for x in xrange(0, len(vrtSublist), y_count)]
if len(vrtSublist) % y_count == 0:
sublist_no = len(vrtSublist)/y_count
else:
sublist_no = (len(vrtSublist)/y_count) + 1
Latlist = []
for slsub in range(0,sublist_no):
output_vrtsublist = s"W:/04 Tools/07 MapMaker/workingfiles/tif" + "_Lat" + str(slsub) + ".vrt"
general.runalg("gdalogr:buildvirtualraster",sublists[slsub],0,False,False,output_vrtsublist, progress=None)
Latlist.append(str(output_vrtsublist))
Now, I have merged each of the 7 .vrt files into single .vrt files; and now, I can see the list of output .vrt files in another list Latlist.
Latlist_no = len(Latlist)
output_vrtfinal = "W:/04 Tools/07 MapMaker/workingfiles/tif" + "_merged.vrt"
general.runalg("gdalogr:buildvirtualraster",Latlist,0,False,False,output_vrtfinal, progress=None)
output_vrtclipped = "W:/04 Tools/07 MapMaker/workingfiles/tif" + ".vrt"
extents_vrtclip = "%f,%f,%f,%f"% (lon, longmax, lat, latmax)
general.runalg("gdalogr:cliprasterbyextent",output_vrtfinal,"",extents_vrtclip,5,4,75,6,1,False,0,False,"",output_vrtclipped, progress=None)
Unfortunately, I am getting an error
Traceback (most recent call last):
IndexError: list index out of range
I am getting this error in the line :
sublists = [vrtSublist[x:x+y_count] for x in xrange(0, len(vrtSublist), y_count)]
How can I solve this issue?
Best Answer
Finally, I solved this issue.
Eventhough the error was displayed as it is in line :
But, actually, the issue was with the line (I found out this after checking the logic of each line by line) :
Here, as per the coordinate values which I given as input, lat was greater than latmax (that is lat > latmax).
But, as per the algorithm in the line :
lat must be smaller than or equal to latmax (that is lat <= latmax).
So, when I changed the input coordinate values such that lat <= latmax and lon <= longmax ; then the algorithm worked correctly. Thus, my above python program was successfully executed.