如何用 Python 獲取當前目錄中的所有子目錄列表?


要遞迴獲取目錄中所有子目錄的列表,可以使用 os.walk 函式。它返回一個三元組,第一個條目是所有子目錄。

你可以按以下方法使用它

import os
subdirs = [x[0] for x in os.walk('.')]
print(subdirs)

你還可以使用 os.listdir 函式列出目錄(僅下級目錄),然後使用 os.path.isdir 函式過濾列表。

例如

import os
d = '.'
subdirs = [os.path.join(d, o) for o in os.listdir(d) if os.path.isdir(os.path.join(d,o))]

更新於: 16-12-2019

11K+ 瀏覽量

開啟你的 職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.