Home > Article > Backend Development > How to List 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>
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>
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>
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!