masalibの日記

システム開発、運用と猫の写真ブログです

Projectのプログラム一覧をエクセルに落とす方法

大量にあるとプログラム一覧を作ることですら大変です。 ちょっとでも楽をするためにプログラム一覧をエクセルにするプログラムを作りました

事前作業

1 . Tree: ディレクトリのツリー構造を表示するためのコマンドラインツールです。ターミナルで tree コマンドを実行すると、カレントディレクトリ以下のディレクトリとファイルが階層構造で表示されます。 Macにはデフォルトでインストールされていないことがありますが、Homebrewなどのパッケージマネージャーを使ってインストールすることができます。

brew install tree

インストール後は、tree コマンドでディレクトリ構造を簡単に表示できます。

2 . openpyxl: openpyxlpythonでエクセルファイルを作成するときに使用します

pip install openpyxl
# pipが入っていない場合
python3 -m pip install openpyxl

出力

treeコマンドで出力するだけです

cd Projectフォルダ
tree > tree_output.txt

出力結果をエクセルにする

import os
from openpyxl import Workbook

def parse_tree_output(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    
    parsed_lines = []
    
    for line in lines:
        # Remove tree symbols and leading spaces
        cleaned_line = line.lstrip().replace("├──", "").replace("└──", "")

        # cleaned_lineに│が含まれている数を取得する
        pipe_count = cleaned_line.count("│")
        indent_level  = pipe_count + 1

        # cleaned_lineから│と全角スペースと半角スペースを削除する
        cleaned_line = cleaned_line.replace("│", "").replace(" ", "").replace(" ", "")

        # Determine indent level
        #indent_level = len(line) - len(line.lstrip())
        #debug log
        #print(f"Indent Level: {indent_level}, Line: {cleaned_line}")

        parsed_lines.append((cleaned_line.strip(), indent_level))
    
    return parsed_lines

def write_to_excel(data, excel_file):
    wb = Workbook()
    ws = wb.active
    ws.title = 'Tree Output'
    
    for line, indent_level in data:
        # Write to Excel adjusting indent level

        ws.cell(row=ws.max_row + 1, column=indent_level + 1, value=line)
    
    wb.save(excel_file)
    print(f"Excel file '{excel_file}' created successfully.")

if __name__ == "__main__":
    tree_file_path = 'tree_output.txt'  # Replace with your Tree command output file path
    excel_file_path = 'tree_output.xlsx'  # Output Excel file path
    
    parsed_data = parse_tree_output(tree_file_path)
    write_to_excel(parsed_data, excel_file_path)

このスクリプトでは、parse_tree_output 関数で tree_output.txt ファイルを読み取り、各行のインデントレベルとパスを抽出します。 その後、create_excel_from_tree_output 関数で、取得したデータを新しいエクセルファイルに書き込みます。エクセルファイルは現在のディレクトリに tree_output.xlsx として保存されます。

不格好ですが加工しやすくなりました