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?
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.
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.
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.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With