[Python] Creating Nested Indexes of Subfolders using Python

Discussão em 'Python' iniciado por Stack, Julho 22, 2025.

  1. Stack

    Stack Membro Participativo

    I am using python to create an index.html page that lists all the files in each folder and subfolder of my static-website. I also want to create the file indexes for the subfolders and their contents.

    I am having trouble directing my python program to the correct folder for each make_index_html action for each folder. I keep having to explicitly write out file locations in order to avoid getting a FileNotFoundError.

    from pathlib import Path

    def make_index_html( path ):
    path = Path(path)

    ## Navigate to inside current folder
    path = path / 'FOLDER A'

    with open( path / 'index.html', 'w' ) as out:

    for file in sorted(list(path.iterdir())):
    out.write( f'<a href="{file.name}">{file.name}</a>\n' )

    if __name__ == '__main__':
    make_index_html('.')

    ## Create the index page for the subfolder
    with open("./FOLDER A/SUBFOLDER B/index.py") as file:
    exec(file.read())



    Here's an example of what I want my site to look like:

    HOME INDEX

    • FOLDER A [click]
    • fodler B
    • index.py

    FOLDER A INDEX

    • file C
    • SUBFOLDER D [click]
    • subfolder e
    • index.py

    SUBFOLDER D INDEX

    • file g
    • file h
    • index.py

    The way I got things to work right now, I have to have an index.py file for every folder and subfolder.

    I realize there has to be a better/simpler way to do this.

    I admit this is such a mess because I'm not as familiar with python as I should be, and I cobbled this together from Google. Please also feel free to direct me to concepts/functions as well so I'm not stumbling around in the dark. Thanks in advance!

    Continue reading...

Compartilhe esta Página