How to List Directory Structures in Python?

Mary-Kate Olsen
Release: 2024-11-04 02:00:02
Original
982 people have browsed it

How to List Directory Structures in Python?

Listing Directory Structures in Python

Obtaining a comprehensive list of files and directories within a specified directory is a common requirement in Python programming. Here's how to accomplish this effectively:

Getting a Hierarchical File and Directory Listing

The os.walk() function provides a powerful method for traversing a directory tree and generating a hierarchical listing of its contents. It takes a starting directory as input and yields three tuples for each level within the directory structure:

  • dirname: The absolute path to the current directory being processed.
  • dirnames: A list of subdirectories within the current directory.
  • filenames: A list of filenames within the current directory.

Example Implementation

<code class="python">import os

for dirname, dirnames, filenames in os.walk('.'):
    # Print path to subdirectories first.
    for subdirname in dirnames:
        print(os.path.join(dirname, subdirname))

    # Print path to filenames.
    for filename in filenames:
        print(os.path.join(dirname, filename))

    # Optional: Modify 'dirnames' to skip subdirectories.
    if '.git' in dirnames:
        dirnames.remove('.git')</code>
Copy after login

This code traverses the current working directory (represented by ".") and prints the full path to all subdirectories and filenames within the directory tree. By default, it recurses into all subdirectories. However, you can modify the dirnames list within the loop to control which subdirectories are explored.

Advanced Usage

  • Excluding directories: The dirnames list can be modified to remove directories from the traversal path. For example, to exclude .git directories, you can remove them from dirnames as shown in the example above.
  • Traversing symbolic links: By default, os.walk() follows symbolic links. To avoid this, set the followlinks parameter to False.
  • Storing file information: The filenames and dirnames tuples can be used to extract additional file information, such as file size and modification time.

The above is the detailed content of How to List Directory Structures 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