【python基础】os.listdir乱序问题

前言

想要获取之前某个目录的有序文件,除了文件名称,其他的比如文件内容、创建时间等都发生了改变,不清楚使用os.listdir是否会改变前后的文件排序。

可以使用帮助文档查看os.listdir的说明

help(os.listdir)

output

The list is in arbitrary order.  It does not include the special
entries '.' and '..' even if they are present in the directory.

可以看出,os.listdir的输出列表的顺序是任意的,不过也可以sort这个list。

复制代码
# alphabetical order
parent_list = os.listdir()
parent_list.sort()
print(parent_list)

# reverse the list
parent_list = os.listdir()
parent_list.reverse()
print(parent_list)

# 1.txt 2.txt 3.txt
files.sort(key= lambda x:int(x[:-4]))
#
path_list.sort(key=lambda x:int(x.split('.')[0])) #对‘.’进行切片,并取列表的第一个值(左边的文件名)转化整数型 
#
dir_list = sorted(dir_list,key=lambda x: os.path.getmtime(os.path.join(file_path, x)))
img_list =sorted(os.listdir(img_path)) #文件名按字母排序
复制代码

 

The order has to do with the way the files are indexed on your FileSystem. If you really want to make it adhere to some order you can always sort the list after getting the files.

参考

1. os.listdir() reading files in a mixed up order

 

posted on   鹅要长大  阅读(1445)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
历史上的今天:
2017-08-17 git log 退出方法

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示