Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List directory tree structure in 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?

like image 962
cinny Avatar asked Oct 09 '22 13:10

cinny


People also ask

How do you find the tree structure in Python?

You can use the os. walk() method to get the list of all children of path you want to display the tree of. Then you can join the paths and get the absolute path of each file.

How do you structure a directory in Python?

Python's OS module provides an another function to create a directories i.e. os. makedirs(name) will create the directory on given path, also if any intermediate-level directory don't exists then it will create that too. Its just like mkdir -p command in linux.

How do I find folder tree structure?

Navigate into the folder in file explorer. Press Shift, right-click mouse, and select "Open command window here". Type tree /f /a > tree. txt and press Enter.

What is directory tree structure?

In computing, a directory structure is the way an operating system arranges files that are accessible to the user. Files are typically displayed in a hierarchical tree structure.


1 Answers

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))
like image 210
dhobbs Avatar answered Oct 21 '22 04:10

dhobbs