Home > Blockchain >  How to get folder and subfolder name alone in JSON format using Python
How to get folder and subfolder name alone in JSON format using Python

Time:03-30

I am trying to get folders and subfolders names alone and dump into JSON. I have explained with sample tree structure and output file which i am expecting. I tried so many ways which is not working as for as now

My Folder tree structure:

|-Folder1
|--Subfolder       
|---Subfolder
|----Subfolder 
|-----Subfolder             

Output format which I am expecting as XYZ.json file.

{
"Userinput0": "x.x",
"Somename": {
    "Folder1": {
        "subfolder": {
            "subfolder": {
                "subfolder": {
                    "subfolder": {
                        "Userinput1": "x",
                        "Userinput2": "Y",
                        "Userinput3": Z
                    }
                }
            }
        }
    }
}

In this case, userinput values input should entered by user.

Could anyone please help me to achieve this. Thanks in advance :)

CodePudding user response:

I created variables so the code is easier to read. I'm certain more skilled coders will code the following with more finesse. This code assumes your folder structure is always the same.

import json

in0  = "x.x"
in1  = "X"
in2  = "Y"
in3  = "Z"
name = "Somename"
f1   = "Folder1"
sf1  = "subfolder"
sf2  = "subfolder"
sf3  = "subfolder"
sf4  = "subfolder"

d = {"Userinput0": in0}
d[name] = {f1: {sf1: {sf2: {sf3: {sf4: {"Userinput1": in1,"Userinput2": in2,"Userinput3": in3, } }}}}}
j = json.dumps(d, indent=5)
print (j)

CodePudding user response:

The scanning the directory structure is a classic recusion problem. You can imagine the directories as a huge tree with subdirectories as intermediate nodes and files as leaves.

To get output in the format you mentioned you can use Head recursion by first looking up current directory elements are files or subdirectories and then making the recursion call if its a subdirectory

  • Related