ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2022-08-17 19:33:26  阅读:180  来源: 互联网

标签:sort listdir parent python list path os 乱序


前言

想要获取之前某个目录的有序文件,除了文件名称,其他的比如文件内容、创建时间等都发生了改变,不清楚使用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

 

标签:sort,listdir,parent,python,list,path,os,乱序
来源: https://www.cnblogs.com/happyamyhope/p/16573345.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有