Directory Tree Structure Print करना
आप os.walk() Method का उपयोग करके उन सभी Children की List प्राप्त कर सकते हैं जिनके Path का Tree आप Display करना चाहते हैं। फिर आप Paths को Join करके प्रत्येक File का Absolute Path प्राप्त कर सकते हैं।
उदाहरण: Basic Tree Printer
import os
def tree_printer(root):
for root, dirs, files in os.walk(root):
for d in dirs:
print(os.path.join(root, d))
for f in files:
print(os.path.join(root, f))
tree_printer('.')
यह आपके Tree में सभी Directories की List पहले Print करेगा और फिर Directory में सभी Files के Paths को Recursively Print करेगा।
उदाहरण Output:
C:\hello\my_folder C:\hello\another_folder C:\hello\my_folder\abc.txt C:\hello\my_folder\xyz.txt C:\hello\another_folder\new.txt ...
Better Visual Tree (Indentation के साथ)
import os
def print_tree(startpath, prefix=''):
for root, dirs, files in os.walk(startpath):
level = root.replace(startpath, '').count(os.sep)
indent = ' ' * 2 * level
print(f'{indent}{os.path.basename(root)}/')
subindent = ' ' * 2 * (level + 1)
for file in files:
print(f'{subindent}{file}')
print_tree('.')
Output Example:
project/
src/
main.py
utils.py
tests/
test_main.py
README.md
requirements.txt
Pathlib का उपयोग (Modern)
from pathlib import Path
def print_tree_pathlib(path, prefix=''):
path = Path(path)
print(f"{prefix}{path.name}/")
for item in sorted(path.iterdir(), key=lambda x: (x.is_file(), x.name)):
if item.is_dir():
print_tree_pathlib(item, prefix + ' ')
else:
print(f"{prefix} {item.name}")
print_tree_pathlib('.')