Home > database >  python: splitting filenames to order sequentially
python: splitting filenames to order sequentially

Time:02-05

I have filenames like this:

'./images/X_0_image0.png',
'./images/X_0_image1.png',
'./images/X_0_image10.png',
'./images/X_0_image100.png',
'./images/X_0_image101.png',

in a directory containing a lot. How do I read the content such that I obtain a list of paths and filenames sorted in ascending order like for a human count, i.e. not having X_0_image100.png appear after X_0_image10.png. I want to store those in a dataframe so that they match the orginal index order in which they were created row wise from 0 index to end.

CodePudding user response:

Here's an option:

# Randomly ordered:
filenames = [
    './images/X_0_image10.png',
    './images/X_0_image0.png',
    './images/X_0_image1.png',
    './images/X_0_image101.png',
    './images/X_0_image100.png',
]

trim_length = len('./images/X_0_image')

sorted_filenames = [
    x[1] for x
    in
    sorted([
        (int(filename.split('.')[1][trim_length-1:]), filename)
        for filename
        in filenames
    ])
]

print(sorted_filenames)
  • Related