Pythonでディレクトリとファイルを階層構造で再帰的にリストアップする(エクセルに貼り付け用)

以下のように、エクセルで階層構造のファイルリストを作成したいときに利用するPythonスクリプトです。

再帰的にフォルダを探索して、ツリー形式で表現します。

スクリプトでの出力は、以下のようにカンマ区切りとなりますので、それをエクセルに貼り付ける際に、メニューの「データ」→「区切り位置」でカンマを選択すると、上記のように貼り付けできます。

Pythonコード

参考ソースは以下のようになります。

import os

# 自分の環境のディレクトリに修正
root_path = r"D:\MyDownload\soft\subs2srs\subs2srs_v29.7\subs2srs"


def list_items(path, step):
    items = os.listdir(path)

    for item in items:

        # フルパスを取得
        full_path = os.path.join(path, item)

        if os.path.isfile(full_path):
            # ファイルの場合
            print("," * step + item)

        elif os.path.isdir(full_path):
            # フォルダの場合
            print("," * step + item)

            # 関数を再帰呼び出し
            list_items(full_path, step + 1)

        else:
            # パスが存在しない場合
            print(None)


list_items(root_path, 0)