python生成文件夹目录树到txt文件

参考原作者 https://blog.csdn.net/xijuezhu8128/article/details/106115939

1. 代码

from pathlib import Path #python自带的包

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:\\research' # 需要生成目录树的文件路径
    generate_tree(Path(path), 0)
    print(tree_str)
    f = open('tree.txt', 'a') # 输出的txt文件路径
    f.write(tree_str)
    f.close()

2. 输出的结果

    |    |    |    |----epoch_30_0.747763.pth
    |    |    |    |----epoch_3_0.845542.pth
    |    |    |    |----epoch_4_0.771097.pth
    |    |    |    |----epoch_5_0.770419.pth
    |    |    |    |----epoch_6_0.760817.pth
    |    |    |    |----epoch_7_0.750074.pth
    |    |    |    |----epoch_8_0.751233.pth
    |    |    |    |----epoch_9_0.757087.pth
    |    |    |----evaluate\
    |    |    |    |----evl.xls
    |    |    |----log\
    |    |    |----runs\
    |    |    |    |----events.out.tfevents.1604333960.DESKTOP.21864.0
    |    |----file304\
    |    |    |----checkpoints\
    |    |    |    |----epoch_10_0.753063.pth
    |    |    |    |----epoch_11_0.751242.pth
    |    |    |    |----epoch_12_0.750930.pth
    |    |    |    |----epoch_13_0.749811.pth
    |    |    |    |----epoch_14_0.750356.pth
    |    |    |    |----epoch_15_0.749778.pth
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值