Skip to main content

Hi,

How to sort files in folder in order of last 5 characters of filename? I'm looping through files in folder and getting last 5 characters of filename but I couldn't find a solution for sorting. Please suggest. 

TIA

I might use a Python script to do the sorting.

import os

def sortByLastFive(mypath):
# get list of files as an array
myfiles = os.listdir(mypath)
# set indices for the myfiles array
first = 0
second = 0
# loop through the array (kind of a bubble sort)
for firstfile in myfiles:
for secondfile in myfiles:
# see if the files should be reversed
if (firstfile[-5:] < secondfile[-5:]):
# reverse the files in the array
mytemp = myfiles[first]
myfiles[first] = myfiles[second]
myfiles[second] = mytemp
second = second + 1
second = 0
first = first + 1
# return the array
return(myfiles)

Then, you can have the script pass back a list for you to loop through. I have tested the script but not the integration with Automation Anywhere.


I will give it a try. Thank you Aaron.


When we execute python function, looks like we can only assign the output to a string variable.


Hi ​@Chou6 ,

you can try this and loop through the list named $lFinalFilenames$ …

String Split and replace to get rid of d and ] from Python output.

 

Output after the Python Code:

 

 

 

 

 

 


@Chou6 just get rid of o and ] in the Python output before split into list... much easier 


Hi ​@Chou6 ,

here is the final version for you… 😁

 

Step 1:

Use the Python code from ​@Aaron.Gleason. (I tested your code in AA and works)

 

Step 2:

Extract text between t and ] from Python output (see L5 on screenshot)

 

Step 3:

Split string with delimiter “,” into list variable. (see L6 on screenshot)

 

Step 4:

Loop through your sorted list of filenames… 😎 (see L7 on screenshot)

 

What do you think ​@Chou6?

 

Cheers

Marc

 


Will give it a try Marc, thank you 🙂 


Reply