user18115 user18115 - 4 months ago 16
Python Question

List directory tree structure using Python

I know that we can use os.walk() to list all sub-directories or all files in a directory. However, I would like to list the full directory tree content:


  • Subdirectory 1:

    • file11

    • file12

    • Sub-sub-directory 11:

      • file111

      • file112



  • Subdirectory 2:

    • file21

    • sub-sub-directory 21

    • sub-sub-directory 22


      • sub-sub-sub-directory 221

        • file 2211






How to best achieve this in Python?

Answer

Here's a function to do that with formatting:

import os

def list_files(startpath):
    for root, dirs, files in os.walk(startpath):
        level = root.replace(startpath, '').count(os.sep)
        indent = ' ' * 4 * (level)
        print('{}{}/'.format(indent, os.path.basename(root)))
        subindent = ' ' * 4 * (level + 1)
        for f in files:
            print('{}{}'.format(subindent, f))