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