How to iterate over files in directory using Python?

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

To iterate over files in a directory using Python, there are several methods available. Here are a few examples:

  1. Using os.listdir():

import os

directory = ‘/path/to/directory’
for filename in os.listdir(directory):
if filename.endswith(‘.txt’):

do something with the file

    print(filename)

2. Using `os.scandir()`:
```python
import os

directory = '/path/to/directory'
with os.scandir(directory) as files:
    for file in files:
        if file.name.endswith('.txt') and file.is_file():
            # do something with the file
            print(file.name)
  1. Using pathlib.Path.glob():

from pathlib import Path

directory = Path(‘/path/to/directory’)
for file in directory.glob(‘*.txt’):

do something with the file

print(file.name)


In all of these examples, we specify the path to the directory we want to iterate over, and then use one of the available methods (`os.listdir()`, `os.scandir()`, or `pathlib.Path.glob()`) to loop through the files in the directory. We can then apply a filter to select only the files we are interested in, based on their file extension or other criteria. Finally, we can do something with each file, such as reading its contents or processing its data.

Tags: