深度遍历,查找目标目录所有符合要求的文件
Topic sourcelogging.basicConfig(filename="log", level=logging.DEBUG)
def findfile_dfs(filename: str, root: str, res: List[str]) -> str:
# 深度遍历查找目标文件
if os.path.isfile(root):
# 判断是否为目标文件,若是则返回其相对路径
if filename in os.path.split(root)[-1]:
return root
else:
# 获取当前路径所有目录和文件
dir_list = os.listdir(root)
# 遍历当前目录
for dir in dir_list:
# 深度遍历查找
path = findfile_dfs(filename, os.path.join(root, dir), res)
# 返回不为None,则找到对应文件
if path:
res.append(path)
# 未找到文件,返回None
return None
if __name__ == '__main__':
# 查找文件根目录
root = "."
# 目标文件名
target_filename = "target"
# 保存目标文件相对路径列表
res = []
try:
findfile_dfs(target_filename, root, res)
except Exception as e:
logging.exception(e)
print(e)
print(res)
- 1
12345