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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章