Using os.walk() for Recursive Directory Traversal in Python
Navigating directories recursively and listing their contents is a common task in Python programming. The os.walk() function provides an efficient way to achieve this goal.
Original Code
The following code demonstrates how to use os.walk() to navigate from the root directory to all subdirectories and print their contents:
#!/usr/bin/python import os import fnmatch for root, dir, files in os.walk("."): print(root) print("") for items in fnmatch.filter(files, "*"): print("..." + items) print("")
This code effectively lists the contents of the current directory and its subdirectories, but it does not differentiate between directories and files.
Desired Output
However, the desired output requires displaying directories as subfolders and files as items within those folders:
A ---a.txt ---b.txt ---B ------c.out
Revised Code
To achieve the desired output, the following revised code employs os.path.basename() to obtain the directory path:
#!/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)
This code first splits the path using os.sep to identify the directory levels. It then prints the directory name with a number of dashes corresponding to its depth, followed by a list of files within that directory with an additional dash for each level.
The above is the detailed content of How can I use os.walk() to create a visually structured directory tree in Python?. For more information, please follow other related articles on the PHP Chinese website!