2

I use os.path to generate a file list from a directory. I am generating a photo gallery from it via Tkinter. However the sorting is completely random. I do not see a greater logic behind the order of the photos, that are displayed from the directory. And when I print the list, it's random as well.

How can I change the order of the list, coming out of this snippet by file name or date modified?

image_list = [os.path.join("/home/pi/fotos/previews",fn) for fn in next(os.walk("/home/pi/fotos/previews"))[2]]

1 Answer 1

1

Soritng by name

You can use the built-in function sorted.

Example:

image_list = [os.path.join("/home/pi/fotos/previews",fn) for fn in next(os.walk("/home/pi/fotos/previews"))[2]]
sorted_list = sorted(image_list, key=str.swapcase)

Sorting by last modified date

You can use os.stat(filename).st_mtime in order to see when the file was last modified.

Example:

folder_path = "/home/pi/fotos/previews"
unsorted_list = [file_name for file_name in next(os.walk(folder_path))[2]]
sorted_list = unsorted_list.sort(key=lambda file_name: os.stat(os.path.join(folder_path,file_name)).st_mtime)
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly. Now all the images are in the right order. Thank you for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.