1

There are answers to the first part of the question and I took help from this answer to represent a directory structure in JSON. However, I also need to read the contents of each file present.

Currently my code is:

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")))

The current output is:

{"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"}]}]}

So basically I want another tag contents whenever a file is encountered.

Can someone help figuring out what goes under the else condition? Or maybe there is some other approach?

1 Answers1

1

Turns out it's pretty simple to get the contents. Being new to Python, I wasn't able to understand it at first. Here is how I solved it.

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")))