Sorting Files Sequentually
QUESTION: I am trying to create an animation of 15 TIFF files I have in a file folder. The files are named sequentually, like this: image1.tif, image2.tif, ..., image14.tif, image15.tif. I obtain the file names with File_Search. But when I cycle through the files in a loop, they are in the wrong order!
Worse than that, they are in the wrong order even if I sort them with the IDL Sort routine! What is wrong with this code?
IDL> files = File_Search('*.tif', COUNT=count) IDL> sortedFiles = files[Sort(files)] IDL> FOR j=0,count-1 DO Print, sortedFiles[j] image1.tif image10.tif image11.tif image12.tif image13.tif image14.tif image15.tif image3.tif image4.tif image5.tif image6.tif image7.tif image8.tif image9.tif
ANSWER: Yes, you are correct that the files that are returned from File_Search are not in any guaranteed order. And to sort these file names correctly the file name number should be the same length for each file, using leading zeros if necessary. The way your files are named is going to make this sorting task more difficult for you, and you should consider naming the files correctly if you can.
But, sometimes this is not possible and we have to carry on anyway. If this is your situation, then you are going to have to extract the file number from each file name, and use the file numbers that you extract from the files to do your sorting. The code will look something like this.
IDL> rootnames = File_Basename(files, '.tif') IDL> numbers = Long(StrMid(rootnames,5)) IDL> sortedFiles = files[Sort(numbers)] IDL> FOR j=0,count-1 DO Print, sortedFiles[j] image1.tif image2.tif image3.tif image4.tif image5.tif image6.tif image7.tif image8.tif image9.tif image10.tif image11.tif image12.tif image13.tif image14.tif image15.tif
Version of IDL used to prepare this article: IDL 7.0.1.