How to iterate over all files in a directory in Python?

Published on Aug. 22, 2023, 12:19 p.m.

To iterate over all files in a directory in Python, you can use the os module to get a list of files and directories and then loop through this list. Here is an example:

import os

# Get the list of files and directories in a directory
directory_path = "/path/to/directory"
for filename in os.listdir(directory_path):
    # Check if the current item is a file
    if os.path.isfile(os.path.join(directory_path, filename)):
        # Do something with the file
        print(filename)

In this example, we first specified the path to the directory we want to iterate through. We then used the os.listdir() function to get a list of the files and directories in this directory. We then looped through this list and checked if each item was a file using the os.path.isfile() function. If the item was a file, we performed some action with it, such as printing its name.

Note that you can also use the os.walk() function to recursively iterate over all files and directories in a directory and its subdirectories. This is useful if you want to perform a recursive operation on all files in a directory tree. Here is an example:

import os

# Recursively iterate through all files in a directory and its subdirectories
directory_path = "/path/to/directory"
for root, dirs, files in os.walk(directory_path):
    for filename in files:
        # Do something with the file
        print(os.path.join(root, filename))

In this example, we used the os.walk() function to get a tuple containing the root directory, a list of subdirectories, and a list of files for each directory in the directory tree. We then looped through the files in each directory and performed some action with them, such as printing their names with the full path included.

Tags: