How to List Files and Directories in a Directory Tree Using Python?

Barbara Streisand
Release: 2024-10-31 00:16:30
Original
355 people have browsed it

How to List Files and Directories in a Directory Tree Using Python?

Listing Files and Directories in a Directory Tree Using Python

To list all files and subdirectories within a directory tree in Python, one can utilize the os.walk() method. This method provides a depth-first traversal of the file system, allowing access to the current directory, its subdirectories, and the files within them.

The os.walk(.) expression initiates the traversal from the current working directory, denoted by the '.' character. The method returns a generator object that iterates over three elements: dirname, dirnames, and filenames.

dirname represents the absolute path of the current directory. dirnames contains a list of all subdirectories in the current directory. filenames holds a list of all files in the current directory.

To print the path to each subdirectory, we iterate over dirnames:

<code class="python">for subdirname in dirnames:
    print(os.path.join(dirname, subdirname))</code>
Copy after login

Similarly, we iterate over filenames to print the path to each file:

<code class="python">for filename in filenames:
    print(os.path.join(dirname, filename))</code>
Copy after login

Advanced usage allows us to exclude certain directories from the traversal by removing them from the dirnames list. For instance, to avoid recursing into '.git' directories:

<code class="python">if '.git' in dirnames:
    dirnames.remove('.git')</code>
Copy after login

This code effectively provides a complete listing of all files and directories within a specified directory tree, making it a valuable utility when working with file systems in Python.

The above is the detailed content of How to List Files and Directories in a Directory Tree Using 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!