Python: Sorted file list

怎甘沉沦 提交于 2021-01-28 13:34:30

问题


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:


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)


来源:https://stackoverflow.com/questions/46332012/python-sorted-file-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!