Python:排序的文件列表

标签 python list sorting path

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

如何更改列表的顺序,按文件名或修改日期从此代码段中出来?

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

最佳答案

按名称排序

您可以使用内置函数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 来查看文件的最后修改时间。

示例:

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:排序的文件列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46332012/

相关文章:

python - PyUnicode_AsUTF8() 段错误

python - 使用 PyDrive 将文件上传到 Google-drive Teamdrive 文件夹

Python:有效计算字典列表中键的唯一值的数量

Python:IndexError:列表索引超出范围错误

c++ - 按 QJsonArray 的子元素之一对 QJsonArray 进行排序

c - 冒泡排序 C 中的链表

python - 如何获得列表某些子集的笛卡尔积,以及整个列表列表的积?

python - Pandas :连接数据框并保留重复索引

python - 您如何概括创建具有许多变量和条件的列表 `if` ?

python - 有选择地解析大数据文件