Home >Backend Development >Python Tutorial >How to List Files and Directories in a Python Directory?

How to List Files and Directories in a Python Directory?

DDD
DDDOriginal
2024-10-31 12:37:02292browse

How to List Files and Directories in a Python Directory?

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:

  1. Import the os module, which provides operating system-related functions.
  2. Invoke the os.walk('.') function. The dot (.) represents the current working directory.
  3. The os.walk() function returns three variables: dirname, dirnames, and filenames.
  4. Iterate over the dirnames list to recursively print the path to each subdirectory.
  5. Iterate over the filenames list to print the path to each file.

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!

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