Python - 再帰的にサブフォルダ一覧とファイル一覧を取得する

指定したディレクトリ内 の サブディレクトリ と ファイル をすべて列挙するには os.walk 関数を使用します。

全てのフォルダとファイルを取得

import os

for root, dirs, files in os.walk(top='./targetDir'):
    for dir in dirs:
        dirPath = os.path.join(root, dir)
        print(f'dirPath = {dirPath}')

    for file in files:
        filePath = os.path.join(root, file)
        print(f'filePath = {filePath}')

全てのファイルのみ取得

ファイルのみ処理したい場合、dirs変数 は必要ありません。
import os

for root, dirs, files in os.walk(top='./targetDir'):
    for file in files:
        filePath = os.path.join(root, file)
        print(f'filePath = {filePath}')

全てのフォルダのみ取得

フォルダのみ処理したい場合、files変数 は必要ありません。
import os

for root, dirs, files in os.walk(top='./targetDir'):
    for dir in dirs:
        dirPath = os.path.join(root, dir)
        print(f'dirPath = {dirPath}')

拡張子を指定して検索

文字列オブジェクト の lower関数 と endswith関数 を利用します。lower関数 で アルファベットを小文字に統一し、endswith関数 でファイル名の末尾を調べます。 endswith関数は 引数に渡した値 と 文字列の末尾 が一致すると True を返します。複数の拡張子を調べたい場合は タプル(tuple) で指定します。

拡張子が '.txt' と '.csv' のファイルを探す

import os

for root, dirs, files in os.walk(top='./targetDir'):
    for file in files:
        if not file.lower().endswith(('.txt', '.csv')):
           continue

        filePath = os.path.join(root, file)
        print(f'filePath = {filePath}')

検索中フォルダの階層(深さ)を取得

文字列オブジェクト の count関数 で パス区切り文字 の個数を数えます。'/' は Unix、'\\' は Windows です。
import os

target = './targetDir'
for root, dirs, files in os.walk(top=target):
    deps = (root.count('/') + root.count('\\')) - (target.count('/') + target.count('\\'))
    print(f'階層 = {deps}')

子フォルダ -> 親フォルダ の順番で取得

通常は 親フォルダ -> 子フォルダ -> 孫フォルダ の順序で一覧を返しますが、 引数 topdown=False を指定すると 孫フォルダ から走査されます。例えば、ファイルとフォルダを全て削除したい場合などに役立ちます。

サブフォルダ から ファイルを列挙

import os

for root, dirs, files in os.walk(top='./targetDir', topdown=False):
    for file in files:
        filePath = os.path.join(root, file)
        print(f'filePath = {filePath}')

    for dir in dirs:
        dirPath = os.path.join(root, dir)
        print(f'dirPath = {dirPath}')

サブフォルダ内の走査が不要な場合

次の記事を参照してください。

検証環境