Python os 模块练习

题目1:递归输出目录结构

需求描述

要求输出 E:\worksp_py\os_test下的文件结构

参考实现

def recursion_file_info(path, indent=0, maxi=-1):
    '''按字典顺序输出目录结构
    :param path: str 路径
    :param indent:int 首次缩进空格——默认为 0,一般不用改变
    :param maxi:int 目录最大层数——默认为 -1,全部展开
    :return:文件目录
    '''

    if maxi != 0:
        try:
            thedir = os.listdir(path)
        except PermissionError:
            # 无权限的文件不作处理
            pass
        else:
            for item in thedir:
                full_path = os.path.join(path, item)
                if os.path.isdir(full_path):
                    print(f"{' ' * indent} + {item} ")
                    recursion_file_info(full_path, indent + 4, maxi - 1)
                elif os.path.isfile(full_path):
                    print(f"{' ' * indent} + {item} ")


file_path = r"E:\worksp_py\os_test"
print(f"按字典顺序输出目录结构 ")
recursion_file_info(file_path, 0, 2)
posted @ 2023-06-18 09:14  晓枫的春天  阅读(23)  评论(0编辑  收藏  举报