![](/img/trans.png)
[英]How can I make a list of files in a directory where the files in that directory are first before files in subdirectories in python?
[英]How can i list the directory files in python?
在对目录中的文件列表进行排序时,我没有按顺序获得 output
import os
arr = sorted(os.listdir(r'D:\\Krish\\syn\\Python\\Washington'))
print(arr)
下面是output:
['1.pdf', '10.pdf', '11.pdf', '12.pdf', '2.pdf', '3.pdf', '4.pdf', '5.pdf', '6.pdf', '7.pdf', '8.pdf', '9.pdf']
如果你想排序为 integer。它有效
sorted(arr, key=lambda filename: int(filename.split('.')[0]))
output 是:
['1.pdf', '2.pdf', '3.pdf', '4.pdf', '5.pdf', '6.pdf', '7.pdf', '8.pdf', '9.pdf', '10.pdf', '11.pdf', '12.pdf']
这就是字符串的排序方式。 我了解您想做什么,并且可以使用自定义比较器来完成。
def compare(item1, item2):
return int(item1.split(".")[0]) - int(item2.split(".")[0])
arr = ['1.pdf', '10.pdf', '11.pdf', '12.pdf', '2.pdf', '3.pdf', '4.pdf', '5.pdf', '6.pdf', '7.pdf', '8.pdf', '9.pdf']
from functools import cmp_to_key
sorted_arr = sorted(arr, key=cmp_to_key(compare))
print(sorted_arr)
这给出:
['1.pdf', '2.pdf', '3.pdf', '4.pdf', '5.pdf', '6.pdf', '7.pdf', '8.pdf', '9.pdf', '10.pdf', '11.pdf', '12.pdf']
如评论中所述,由于文件名是字符串,因此列表按字典顺序排序。
你可以试试这个:
arr = sorted(os.listdir(r'D:\Krish\syn\Python\Washington'), key=lambda f: int(f[:f.index('.')]))
key
参数是 function,已sorted
的 function 使用它来确定顺序。
在上面的代码中,我传递的 function 获取句点之前的所有字符,并将它们转换为 integer。
所以"10.pdf"
将被转换为10
(作为整数)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.