将目录下的所有文件输出为树结构

该Python代码段用于创建当前工作目录的文件和子目录结构,以Markdown格式表示。它遍历指定路径,递归地构建树形表示,并将结果保存到file_tree.md文件中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

工具向,用python编写。

以下是代码:

import os

def generate_tree(path, level=0):
    tree = ""
    folder_name = os.path.basename(path)
    if level == 0:
        tree += f"{folder_name}\n"
    else:
        tree += f"{'  ' * level}├── {folder_name}/\n"
    items = os.listdir(path)
    dirs = [item for item in items if os.path.isdir(os.path.join(path, item))]
    files = [item for item in items if not os.path.isdir(os.path.join(path, item))]
    for item in sorted(dirs) + sorted(files):
        if os.path.isdir(os.path.join(path, item)):
            tree += generate_tree(os.path.join(path, item), level+1)
        else:
            tree += f"{'  ' * (level+1)}├── {item}\n"
    return tree

folder_path = os.getcwd()
tree = generate_tree(folder_path)

with open("file_tree.md", "w", encoding="utf-8") as f:
    f.write(tree)

效果展示:
在这里插入图片描述
转化为:

stablediffusion-infinity
  ├── .vscode/
    ├── settings.json
  ├── 3rd/
    ├── outpur_dir_structure.py
  ├── PyPatchMatch/
    ├── __pycache__/
      ├── patch_match.cpython-39.pyc
    ├── csrc/
      ├── inpaint.cpp
      ├── inpaint.h
      ├── masked_image.cpp
      ├── masked_image.h
      ├── nnf.cpp
      ├── nnf.h
      ├── pyinterface.cpp
      ├── pyinterface.h
    ├── examples/
      ├── images/
        ├── forest.bmp
        ├── forest_pruned.bmp
      ├── .gitignore
      ├── cpp_example.cpp
      ├── cpp_example_run.sh
      ├── py_example.py
      ├── py_example_global_mask.py
    ├── .gitignore
    ├── LICENSE
    ├── Makefile
    ├── README.md
    ├── libpatchmatch.dll
    ├── opencv_world460.dll
    ├── patch_match.py
    ├── travis.sh
  ├── __pycache__/
    ├── perlin2d.cpython-39.pyc
    ├── postprocess.cpython-39.pyc
    ├── utils.cpython-39.pyc
  ├── css/
    ├── w2ui.min.css
  ├── js/
    ├── fabric.min.js
    ├── keyboard.js
    ├── mode.js
    ├── outpaint.js
    ├── proceed.js
    ├── setup.js
    ├── toolbar.js
    ├── upload.js
    ├── w2ui.min.js
    ├── xss.js
  ├── models/
    ├── v1-inference.yaml
    ├── v1-inpainting-inference.yaml
  ├── .gitattributes
  ├── README.md
  ├── app.py
  ├── canvas.py
  ├── config.yaml
  ├── convert_checkpoint.py
  ├── file_tree.md
  ├── index.html
  ├── packages.txt
  ├── perlin2d.py
  ├── postprocess.py
  ├── process.py
  ├── requirements.txt
  ├── utils.py

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猫咪钓鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值