Home > Backend Development > Python Tutorial > 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?

Mary-Kate Olsen
Release: 2024-11-07 04:31:02
Original
971 people have browsed it

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)
Copy after login

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.

The above is the detailed content of How can I use `os.walk()` to create a structured directory listing with depth indicators in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template