python快速遍历文件夹
时间: 2025-02-03 19:48:42 浏览: 62
### 使用Python高效遍历文件夹
为了实现高效的文件夹遍历,在Python中有多种方法可供选择。其中一种常用的方式是利用`os.walk()`函数,该函数能够递归地遍历指定路径下的所有子目录和文件[^1]。
```python
import os
def traverse_directory(directory_path):
for root, dirs, files in os.walk(directory_path):
print(f'当前目录: {root}')
print('包含的子目录:', dirs)
print('包含的文件:', files)
traverse_directory('/path/to/directory')
```
另一种更为简洁且性能更优的选择是使用`pathlib.Path.rglob()`方法来查找特定模式匹配的所有文件。这种方法不仅语法更加直观易懂,而且执行速度也更快[^2]。
```python
from pathlib import Path
def find_files_with_pattern(directory_path, pattern='*'):
path = Path(directory_path)
matching_files = list(path.rglob(pattern))
for file in matching_files:
print(file.absolute())
find_files_with_pattern('/path/to/directory', '*.txt')
```
对于追求极致效率的情况,还可以考虑采用多线程或多进程的方式来加速大容量数据集上的操作。通过并行处理不同部分的数据,可以在一定程度上减少总的运行时间[^3]。
```python
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
def process_file(file_path):
# 对单个文件进行处理的操作
pass
def parallel_process_files(directory_path, max_workers=5):
path = Path(directory_path)
all_files = [file.absolute() for file in path.rglob('*')]
with ThreadPoolExecutor(max_workers=max_workers) as executor:
executor.map(process_file, all_files)
parallel_process_files('/path/to/large_dataset')
```
阅读全文
相关推荐













