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.
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!