【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;
完
各美其美,美美与共,不和他人作比较,不对他人有期待,不批判他人,不钻牛角尖。
心正意诚,做自己该做的事情,做自己喜欢做的事情,安静做一枚有思想的技术媛。
版权声明,转载请注明出处:https://www.cnblogs.com/happyamyhope/
心正意诚,做自己该做的事情,做自己喜欢做的事情,安静做一枚有思想的技术媛。
版权声明,转载请注明出处:https://www.cnblogs.com/happyamyhope/
分类:
python
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
2017-08-17 git log 退出方法