solution_026.py

#!/usr/bin/python3
# ===================================================================
# display directory tree
# ===================================================================

import re
import os

# -------------------------------------------------------------------
# ---- display the regular files in a directory and sub-directories
# ---- indent file names based on their depth in the tree
# ---- if maxdepth = 0 the complete tree will be output
# ---- else only to the depth specified
# -------------------------------------------------------------------

def displayDirectory(rootdir,depth,maxdepth):

    # ---- tree depth exceeded?

    if maxdepth != 0 and depth > maxdepth:
        return

    # ---- display directory name

    print(f'{"--" * depth} {rootdir}')

    # ---- make sure directory ends in '/'

    if not re.search('\/$',rootdir):
        rootdir = rootdir + '/'

    # --- get a list of entries in the directory

    files = os.listdir(rootdir)

    # --- remove all hidden and other non-display files
    # --- display the others and process sub-directories

    for f in files:

        ff = rootdir + f       # full path + name

        # ---- skip links

        if os.path.islink(ff):
            continue

        # ---- skip hidden directory entries

        if re.search('^\.',f): 
            continue

        # ---- display sub-directory?

        if os.path.isdir(ff):
            displayDirectory(ff,depth+1,maxdepth)

        # ---- display file name

        if os.path.isfile(ff):
            print(f'{"   " * depth}{f}')


# -------------------------------------------------------------------
# ----- main
# -------------------------------------------------------------------


rootdir = '/home/tom'

displayDirectory(rootdir,0,4)