Is there some way to alphanumerically sort through the folders inside of a given directory path while accounting for the decimals as well? (I'm currently using Python3.10 and am on Windows 11).
I'm making a program that when given a directory path containing folders in it, will iterate through each of those folders and iterate through each of the .jpgs in those folders. Each of those .jpgs are to be renamed starting from i, where i = 1 and up until the last .jpg that is founded. However, I am having issues with iterating through each of those folders alphanumerically (I believe that's the term?).
I have technically iterated through the folders alphanumerically like in Example 1.
Example 1 (Correct): Ch 1, Ch 2, Ch 3, Ch 10, Ch 11
Example 2 (Incorrect): Ch 1, Ch 10, Ch 11, Ch 2, Ch 3
But I say technically because I've done so using key=len
in the for loop in the code provided below. And (I believe) that only sorts things by the character length. Thus, it does not account for decimals such as in Example 4. I got key=len from this post.
Example 3 (Correct): Ch 1, Ch 2, Ch 2.5, Ch 8, Ch 10, Ch. 21.5, Ch 234
Example 4 (Incorrect): Ch 1, Ch 2, Ch 8, Ch 10, Ch 2.5, Ch 234, Ch. 21.5
def fnSortThroughFiles(self):
#Prompts file dialog for user to choose a directory path
chosenPath = filedialog.askdirectory()
i = 0
#For all the files in a sorted list containing each directory path in chosenPath
for file in sorted(os.listdir(chosenPath), key=len):
i = i+1
#prints name of the folder
print( str(i) + ". " + file)
#Make a for loop that iterates through a concatenation of chosenPath and file to rename .jpgs and move them all into one single folder rather than being in separate folders.
#Outputs the total amount of files (in this case folder) founded inside of chosenPath (not the files inside of chosenPath's files)
print("\nA total of " + str(i) + " items are in the directory " + chosenPath)
Here are some pictures I've attached if needed.
Visual Aid 1: User's Chosen Path