Python:排序文件列表 [英] Python: Sorted file list

查看:41
本文介绍了Python:排序文件列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用os.path从目录生成文件列表.我正在通过Tkinter从中生成一个照相馆.但是,排序是完全随机的.从目录中显示的照片顺序后面看不到更大的逻辑.当我打印列表时,它也是随机的.

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]]

推荐答案

按名称排序

您可以使用已排序的内置函数.

Soritng by name

You can use the built-in function sorted.

示例:

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)

按上次修改日期排序

您可以使用os.stat(filename).st_mtime来查看文件的最后修改时间.

Sorting by last modified date

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

示例:

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)

这篇关于Python:排序文件列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆