LoginSignup
0
1

More than 1 year has passed since last update.

Pythonスクリプトで、フォルダからファイルツリーを作成する

Last updated at Posted at 2023-04-10

前回作ったhtmlファイルのフォルダから、ファイルツリーを作成する。

import os

def extract_text_between(file_path):
    start_string = "<h1>"
    end_string ="</h1>"
    with open(file_path, 'r', encoding='utf-8') as file:
        text = file.read()

    start_index = text.find(start_string)

    if start_index == -1:  # 開始文字列が見つからない場合
        return None

    start_index += len(start_string)  # 開始文字列の直後から検索開始
    end_index = text.find(end_string, start_index)

    if end_index == -1:  # 終了文字列が見つからない場合
        return None

    return text[start_index:end_index]

def create_file_tree_html(path, relative_path=""):
    html = ""
    
    for entry in os.scandir(path):
        if entry.is_file():
            file_path = os.path.join(relative_path, entry.name)
            file_name = extract_text_between(file_path)
            html += f'<li><span class="file" onclick="onfile(this)" data-filename="{file_path}">{file_name}</span></li>'
        elif entry.is_dir():
            sub_html = create_file_tree_html(entry.path, os.path.join(relative_path, entry.name))
            html += f'<p class="folder" onclick="onfolder(this)">{entry.name}</p><ul>{sub_html}</ul>'

    return html

def main():
    folder_path = "html-folder"
    output_path = "output.html"

    file_tree_html = create_file_tree_html(folder_path, folder_path)

    with open(output_path, "w") as output_file:
        output_file.write(f"""
<!DOCTYPE html>
<html>
    <head>
        <style>
            ul {{
                display: none;
                padding-left: 10px;
                list-style-type: none;
            }}
            li {{
                margin-bottom: 5px;
            }}
            .folder,
            .file {{
                cursor: pointer;
            }}
            .folder:before {{
                content: "";
                display: inline-block;
                margin-right: 6px;
            }}

            .folder.open:before {{
                content: "";
            }}
            .selected {{
             font-weight: bold; /* 太字にするスタイルを追加 */
            }}
            .file:hover {{
                text-decoration: underline; /*ファイル名にカーソルを載せたときに下線を表示*/
            }}
        </style>
        <script>
            let selectedFile = null;
            function onfile(th){{
                const fname = th.getAttribute('data-filename');
                window.parent.setfiletomain(fname);
                if (selectedFile) {{
                    selectedFile.classList.remove('selected');
                }}
                th.classList.add('selected');
                selectedFile = th;
            }}
            function onfolder(th){{
                th.classList.toggle('open');
                const el = th.nextElementSibling;
                if (el.style.display === '' || el.style.display === 'none') {{
                    el.style.display = 'block';
                }} else {{
                    el.style.display = 'none';
                }}
            }}
        </script>
    </head>
    <body>
    {file_tree_html}
    </body>
</html>
""")

if __name__ == "__main__":
    main()
  • まずmain()関数を読んでいる。
if __name__ == "__main__":
    main()
  • main()関数では、ファイルツリーにしたいフォルダのパスと、完成したファイルツリーのを書き込むhtmlファイルのパスがある。
    パスを変えることはあまりないと思うので、引数にはしなかった。

  • 完成したファイルツリーのhtmlファイルには、styleや、フォルダの展開、ファイルの中身の表示などの機能のscriptが入るようにしている。

  • create_file_tree_html()関数ではフォルダの中身を再起的に探索して、ファイルツリーを書き起こしている。

  • extract_text_between()関数はファイルの中からh1タグのタイトルを見つけてきて返すようにしている。
    タイトルをファイルツリーに表示する。
    フォルダー名はそのまま、ファイルツリーに表示すれば良いが、ファイル名は拡張子などが表示されるのが嫌なのでファイルの中からタイトルを取ってくるようにした。

※前回ファイルツリーを作成したときに書いた説明と被る箇所は、省略している。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1