更新日志:
- [2019-08-21]
- 修改 yield from list_paths(tmp_path, depth - 1, suffix) 中参数位置的错误
- [2019-07-17]
- 添加 v 2.0 版,修复 v 1.0 版本的 depth_count += 1 引起的 bug
- v 2.0 版本 添加只显示指定后缀的文件的功能
- 修改文章名称为《【Python】—— 遍历目录下的文件》
- 删除旧版的表格式描述信息,添加 更新日志 和 说明
- [2018-09-19]
- v 1.0 版本发布
说明:
- GitHub地址:get_paths.py
- 《【Python】—— 遍历目录下的文件》:https://blog.csdn.net/maixiaochai/article/details/82778832
版本 v 2.0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: : get_paths.py
# @Date : 2019-07-17 16:19:38
# @Author : MaiXiaochai
# Email : maixiaochai@outlook.com
# GitHub : https://github.com/MaiXiaochai
# @GitPage : https://maixiaochai.github.io
from os import listdir
from os.path import isdir, splitext
def list_paths(dir_path, depth=0, suffix=None):
"""
1) Generator。
2) 遍历 dir_path 目录下 所有后缀为 suffix 的文件的路径。
3) 注意:这里的路径使用'/'。
:param dir_path: str 要遍历的目录路径
:param depth: int 扫描的深度 0:当前目录,1:当前目录的下一级目录
:param suffix: str 文件后缀,如 ".py" 或者 "py"
:return: str 文件路径
"""
# 设定当前目录的表示值
current_dir_level = 0
dir_path = dir_path if dir_path.endswith("/") else dir_path + "/"
suffix = suffix if suffix.startswith('.') else '.' + suffix
for _path in listdir(dir_path):
tmp_path = dir_path + _path
if isdir(tmp_path):
if current_dir_level < depth:
yield from list_paths(tmp_path, depth - 1, suffix)
elif splitext(tmp_path)[-1] == suffix:
yield tmp_path
def demo():
test_path = './'
depth = 1 # 当前目录和下一级目录
suffix = "py" # 搜索后缀为"py"的文件
res = list_paths(test_path, depth, suffix)
for i in res:
print(i)
if __name__ == "__main__":
demo()
版本 v 1.0
# -*- coding: utf-8 -*-
import os
def get_paths(dir_path, depth=None):
"""
生成器。
遍历指定目录下的所有非目录文件, 不会列出目录路径。
注意:这里的路径使用'/'。
:param dir_path: str/要遍历的目录路径
:param depth: int/扫描的深度 0:当前目录,1:当前目录的下一级目录
:return: str/文件路径, 若当前深度下未发现文件,则不返回。
"""
depth_count = 0
depth = int(depth) if depth else 0
dir_path = dir_path if dir_path.endswith('/') else dir_path + '/'
for path in os.listdir(dir_path):
tmp_path = dir_path + path
if os.path.isdir(tmp_path):
if depth_count < depth:
depth_count += 1
yield from get_paths(tmp_path + '/', depth - 1)
else:
yield tmp_path
if __name__ == "__main__":
the_path = './'
for i in get_paths(the_path, 2):
print(i)