深度阅读

How to iterate over files in directory using Python?

作者
作者
2023年08月22日
更新时间
13.26 分钟
阅读时间
0
阅读量

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.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。