Listing Directory Trees in Python
Determining a directory's contents, including files and subdirectories, is a common programming task. Python offers a straightforward solution to achieve this using the os.walk() function.
How to List Files and Directories in a Directory with Python:
To list all files and directories within a given directory using Python, follow these steps:
Example Code:
<code class="python">import os for dirname, dirnames, filenames in os.walk('.'): # Print path to subdirectories. for subdirname in dirnames: print(os.path.join(dirname, subdirname)) # Print path to files. for filename in filenames: print(os.path.join(dirname, filename))</code>
Advanced Usage:
This code snippet can be modified to suit specific needs. For instance, it can be customized to avoid recursing into certain directories. The example code excludes subdirectories named '.git' by removing them from the dirnames list.
The above is the detailed content of How to List Files and Directories in a Python Directory?. For more information, please follow other related articles on the PHP Chinese website!