python生成某个文件夹的目录树

1. 使用背景

一些情况下我们想要生成某个工程文件夹的文件目录,写在文档里面逐一说明每个文件的功能,这是如果能自动生成文件树就是一件很方便的事。

2. 代码

在如下代码中,只需要给定path目录就可以。

from pathlib import Path

tree_str = ''
def generate_tree(pathname, n=0):
    global tree_str
    if pathname.is_file():
        tree_str += '    |' * n + '-' * 4 + pathname.name + '\n'
    elif pathname.is_dir():
        tree_str += '    |' * n + '-' * 4 + \
            str(pathname.relative_to(pathname.parent)) + '\\' + '\n'
        for cp in pathname.iterdir():
            generate_tree(cp, n + 1)

if __name__ == '__main__':
    path = 'D:/xxx/xxx/xxx'
    generate_tree(Path(path), 0)
    print(tree_str)

3. 结果例子

----upernet\
    |----dataloaders\
    |    |----custom_transforms.py
    |    |----custom_transforms.pyc
    |    |----datasets\
    |    |    |----cityscapes.py
    |    |    |----combine_dbs.py
    |    |    |----csot.py
    |    |    |----csot.pyx
    |    |    |----pascal.py
    |    |    |----sbd.py
    |    |----utils.py
    |----doc\
    |    |----deeplab_resnet.py
    |    |----deeplab_xception.py
    |    |----results.png
    |----example\
    |    |----compare_result.py
    |    |----face_convert.py
    |    |----merge_bn.py
    |    |----seg_convert.py
    |    |----verify_deploy.py
    |    |----verify_deploy.py.bak
    |----modeling\
    |    |----aspp.py
    |    |----backbone\
    |    |    |----drn.py
    |    |    |----mobilenet.py
    |    |    |----modified_resnet.py
    |    |    |----resnet.py
    |    |    |----se_ad_modified_resnet.py
    |    |    |----se_modified_resnet.py
    |    |    |----se_module.py
    |    |    |----se_resnet.py.orig
    |    |    |----xception.py
    |    |----decoder.py
    |    |----deeplab.py
    |    |----sync_batchnorm\
    |    |----UperModule.py
    |    |----UperModule_tmp.py
    |    |----upernet.py
    |    |----upernet_tmp.py
    |----pretrained\
    |    |----resnet18-imagenet.pth
    |    |----resnet50-imagenet.pth
    |----utils\
    |    |----calculate_weights.p
    |    |----loss.py
    |    |----loss_half.py
    |    |----lr_scheduler.py
    |    |----metrics.py
    |    |----saver.py
    |    |----summaries.py
    |----options.py
    |----readme.md
    |----test.py
    |----train.py
    |----train_1350L.sh
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值