Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

使用python写个脚本,生成目录的树形结构到一个json中

  1. User

    使用python写个脚本,生成目录的树形结构到一个json中

  2. Assistant

    这是一个用Python实现生成目录的树形结构,并将其保存到JSON文件中的脚本:

    import os
    import json
    
    def build_tree(path):
        tree = {}
        if os.path.isfile(path):
            return os.path.basename(path)
        elif os.path.isdir(path):
            for item in os.listdir(path):
                sub_path = os.path.join(path, item)
                tree[item] = build_tree(sub_path)
        return tree
    
    root_dir = 'path/to/directory'
    tree = build_tree(root_dir)
    
    with open('tree.json', 'w') as f:
        json.dump(tree, f, indent=4)
    

    使用该脚本,只需将“path/to/directory”替换为您要生成树形结构的目录,并运行脚本。树形结构将被保存到一个名为“tree.json”的文件中,在该文件中,您可以轻松查看整个目录结构的树形表示。

  3. User

    我希望将目录用键值对的形式表示,文件以列表形式表示

  4. Assistant

    好的,这是更新后的脚本,它将目录表示为键值对,文件以列表形式表示:

    import os
    import json
    
    def build_tree(path):
        tree = {}
        if os.path.isfile(path):
            return os.path.basename(path)
        elif os.path.isdir(path):
            for item in os.listdir(path):
                sub_path = os.path.join(path, item)
                if os.path.isfile(sub_path):
                    if 'files' not in tree:
                        tree['files'] = []
                    tree['files'].append(item)
                else:
                    tree[item] = build_tree(sub_path)
        return tree
    
    root_dir = 'path/to/directory'
    tree = build_tree(root_dir)
    
    with open('tree.json', 'w') as f:
        json.dump(tree, f, indent=4)
    

    这个脚本与之前的脚本基本相同,只是增加了一些逻辑来处理目录和文件的区别。现在,目录被表示为键值对,其中每个键对应一个子目录,而文件则以列表形式表示,并作为“files”键的值。

    您只需要替换“path/to/directory”为您想要表示为树形结构的目录,运行脚本,它将生成一个名为“tree.json”的文件,其中包含您的目录结构以JSON格式表示。