How to Use Python Walk Directory to Print Directory Structure?
I am using os.walk()
to recursively traverse directories in Python, but I need to format the output in a specific way.
Here is my current code:
#!/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("")
Current Output:
.
...Python_Notes
...pypy.py
...pypy.py.save
...classdemo.py
....goutputstream-J9ZUXW
...latest.py
...pack.py
...classdemo.pyc
...Python_Notes~
...module-demo.py
...filetype.py
./packagedemo
...classdemo.py
...__init__.pyc
...__init__.py
...classdemo.pyc
Desired Output:
A
---a.txt
---b.txt
---B
------c.out
In the output, A
and B
are directories, and the rest are files. How can I achieve this formatting with os.walk()
in Python?
I’ve worked quite a bit with formatting directory outputs using os.walk
, and I found a neat way to handle it with recursive indentation. This approach is straightforward and visually separates directories and files based on their depth in the structure.
import os
def print_dir_structure(path, level=0):
for root, dirs, files in os.walk(path):
indent = '---' * level
print(f"{indent}{os.path.basename(root)}")
for file in files:
print(f"{indent}---{file}")
# Call the function for the current directory
print_dir_structure(".")
This solution works well if you want to highlight the hierarchical structure of your directory using indentation. It’s one of my go-to methods for working with the python walk directory structure.
@madhurima_sil’s solution is great! I’ve tried something slightly different in my projects. Instead of relying purely on recursive indentation, I like to use os.path.relpath
. It helps in computing relative paths, making the structure feel more aligned with the actual directory layout.
import os
def print_dir_structure(path):
for root, dirs, files in os.walk(path):
# Get relative path of the directory
rel_path = os.path.relpath(root, path)
if rel_path == ".":
print("A") # Root directory
else:
print(f"---{rel_path.replace(os.sep, '')}")
for file in files:
print(f"---{file}")
# Call the function for the current directory
print_dir_structure(".")
This approach enhances the readability of the output when dealing with the python walk directory by leveraging relative paths. It feels more intuitive, especially when working with nested structures.
Both approaches are really effective. Personally, I prefer a method where directories and files are handled separately for more control over the display format. This is particularly useful if you want to apply unique formatting or even add metadata later on.
import os
def print_dir_structure(path):
for root, dirs, files in os.walk(path):
if root == path:
print("A") # Root directory
else:
print(f"---{os.path.basename(root)}") # Subdirectories
for file in files:
print(f"---{file}")
# Call the function for the current directory
print_dir_structure(".")
This solution provides more flexibility when working with the python walk directory structure, especially if your project requires handling directories and files separately.