博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Python 递归

Posted on 2023-08-07 22:34  steve.z  阅读(5)  评论(0编辑  收藏  举报
#
#   py_recursive.py
#   py_learn
#
#   Created by Z. Steve on 2023/8/7 21:28.
#

# 需求: 通过递归查找一个目录下的所有目录和文件 os 模块下的三个方法: 1. os.listdir() 2. os.path.isdir() os.path.isdir(path) 如果 path 是 现有的 目录,则返回
# True。本方法会跟踪符号链接,因此,对于同一路径,islink() 和 isdir() 都可能为 True。 3. os.path.exists() os.path.exists(path) 如果 path
# 指向一个已存在的路径或已打开的文件描述符,返回 True。对于失效的符号链接,返回 False。
# 在某些平台上,如果使用 os.stat() 查询到目标文件没有执行权限,即使 path 确实存在,本函数也可能返回 False。

import os


def list_path_recur(url):
    if not os.path.exists(url):
        print(r"路径 \"{url}\" 不存在")
        return
    else:
        # 递归展示目录和文件
        r_list = os.listdir(url)
        for item in r_list:
            item_full = url + "/" + item
            if os.path.isdir(item_full):
                print(item)
                list_path_recur(item_full)
            else:
                print(item)


if __name__ == "__main__":
    url = input("请输入一个路径:")
    list_path_recur(url)