How can I use os.walk() to create a visually structured directory tree in Python?

Patricia Arquette
Release: 2024-11-08 22:06:02
Original
724 people have browsed it

How can I use os.walk() to create a visually structured directory tree in Python?

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

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

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

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!

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