"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How can I use `os.walk()` to create a structured directory listing with depth indicators in Python?

How can I use `os.walk()` to create a structured directory listing with depth indicators in Python?

Published on 2024-11-09
Browse:361

How can I use `os.walk()` to create a structured directory listing with depth indicators in Python?

Navigating Directories Recursively with os.walk() in Python

Seeking to create more structured directory listings, a developer attempted to modify their code to display directories as capitalized titles with dashed lines indicating depth and files beneath them. However, their initial approach yielded incomplete results.

To address this challenge, we can utilize Python's os.sep attribute to delineate the path components correctly. Here's an improved solution:

#!/usr/bin/python
import os

# traverse root directory, and list directories as dirs and files as files
for root, dirs, files in os.walk("."):
    path = root.split(os.sep)
    print((len(path) - 1) * '---', os.path.basename(root))
    for file in files:
        print(len(path) * '---', file)

In this revised code, we split the path using os.sep as the delimiter, which accommodates both Windows and Unix file systems. By subtracting 1 from the length of the path, we can obtain the depth of the current level and display the appropriate number of dashed lines.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3