Python-将目录结构表示为JSON,并且还读取每个文件的内容

时间:2019-02-28 19:57:42

标签: python json

问题的第一部分有答案,我从this答案中获得了帮助,以表示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条件下会发生什么吗?也许还有其他方法?

1 个答案:

答案 0 :(得分:0)

事实证明,获取内容非常简单。作为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")))