【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 2022-08-17 19:08  鹅要长大  阅读(1216)  评论(0编辑  收藏  举报

导航