Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python: splitting filenames to order sequentially

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading