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:
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>
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
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!