问题
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