
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
List Directory Tree Structure in Python
The given task is to list the directory tree structure, i.e., we need to print the hierarchy of folders and files starting from a specified root directory. This is similar to how the tree command works in Linux or Windows by showing nested folders and files in a structured and indented format.
In this article, we will see all the possible methods in Python to list the directory tree structure.
Using os.walk() Method
The os.walk() method in Python is used to generate the file names and folder names in a directory tree by parsing through the tree in either a top-down or bottom-up approach.
Example
Following is the example, which shows how to use the os.walk() method of the os module to list the directory tree structure of the specified input directory path -
import os def list_dir_tree(start_path): for root, dirs, files in os.walk(start_path): # Determine indentation level level = root.replace(start_path, '').count(os.sep) indent = ' ' * 4 * level # Print folder name print(f'{indent}{os.path.basename(root)}/') sub_indent = ' ' * 4 * (level + 1) # Print files in the folder for f in files: print(f'{sub_indent}{f}') # Example usage list_dir_tree(r"D:\Tutorialspoint\sample")
Following is the output of the above program -
sample/ folder1/ sample1.txt sample2.txt folder2/ sample.txt
Using pathlib.Path.iterdir() method
The pathlib.Path.iterdir() method in Python is used to iterate over the contents of a directory. It returns an iterator of all files and subdirectories in a given directory and can be used recursively to build a directory tree structure in an object-oriented way.
Example
Below is an example that shows how to use pathlib.Path.iterdir() method of the pathlib module to list the directory tree structure of the specified input directory path -
from pathlib import Path def list_tree(path, level=0): for item in sorted(path.iterdir()): print(' ' * level + item.name) if item.is_dir(): list_tree(item, level + 1) # Example usage list_tree(Path(r"D:\Tutorialspoint\sample"))
Here is the output of the above program -
folder1 sample1.txt sample2.txt folder2 sample.txt