首页 > 解决方案 > Python - 将目录结构表示为 JSON 并读取每个文件的内容

问题描述

问题的第一部分有答案,我从这个答案中得到帮助来表示 JSON 中的目录结构。但是,我还需要阅读存在的每个文件的内容。

目前我的代码是:

import os
import json

def path_to_dict(path):
    d = {'name': os.path.basename(path)}
    if os.path.isdir(path):
        d['type'] = "directory"
        d['children'] = [path_to_dict(os.path.join(path,x)) for x in os.listdir\
(path)]
    else:
        d['type'] = "file"
        #contents =  Something to read the contents??
        #d['contents'] = contents

    return d

print (json.dumps(path_to_dict("F:\\myfolder")))

当前输出为:

{"name": "myfolder", "type": "directory", "children": [{"name": "data", "type": "directory", "children": [{"name": "xyz.txt", "type": "file"}]}, {"name": "text", "type": "directory", "children": [{"name": "abc.txt", "type": "file"}]}]}

所以基本上contents每当遇到文件时我都想要另一个标签。

有人可以帮助弄清楚在这种else情况下会发生什么吗?或者也许还有其他方法?

标签: pythonjson

解决方案


事实证明,获取内容非常简单。作为 Python 新手,起初我无法理解它。这是我解决它的方法。

import os
import json

def path_to_dict(path):
    d = {'name': os.path.basename(path)}
    if os.path.isdir(path):
        d['type'] = "directory"
        d['children'] = [path_to_dict(os.path.join(path,x)) for x in os.listdir\
(path)]
    else:
        d['type'] = "file"
        with open('data.txt', 'r') as myfile:
             contents=myfile.read().replace('\n', '')
        d['contents'] = contents

    return d

print (json.dumps(path_to_dict("F:\\myfolder")))

推荐阅读