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

标签 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 条件下会发生什么吗?或者也许还有其他方法?

最佳答案

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

关于Python - 将目录结构表示为 JSON 并读取每个文件的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54933319/

相关文章:

python - 减小 Keras LSTM 模型的大小

python - 如何导入 boto3 ssm ParameterNotFound 异常?

python - sys 模块位于哪里,或者如何在 Win 11 和 Python 中找到它

javascript - 如何计算子对象的数量并将计算出的索引传递给子对象?

javascript - 在 Angular js 中过滤来自 json 或服务器的数据

python - 将 Python 函数转换为 C++ 函数

python - virtualenv 与 setup.py install --user

java - 使用 Gson 反序列化通用集合

c# - asp.net如何反序列化json

javascript - 在项目启动时从 $http.GET 设置 Angularjs 常量