Python 代码片段摘记

1. 文件树

def print_tree(root, prefix="", only_dir=False, file=None):
    files = os.listdir(root)
    files.sort()
    for idx, name in enumerate(files):
        path = os.path.join(root, name)
        if only_dir and not os.path.isdir(path):
            continue
        connector = "└── " if idx == len(files) - 1 else "├── "
        line = prefix + connector + name
        if file:
            print(line, file=file)
        print(line)
        if os.path.isdir(path):
            extension = "    " if idx == len(files) - 1 else "│   "
            print_tree(path, prefix + extension, only_dir=only_dir, file=file)

if __name__ == "__main__":
    path = r"Your_path"
    with open("tree.txt", "w", encoding="utf-8") as f:
        print_tree(path, only_dir=True, file=f)
        # print_tree(path, only_dir=False, file=f)
posted @ 2025-12-02 11:00  Qiansui  阅读(0)  评论(0)    收藏  举报