![](/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.