'How to get folder and subfolder name alone in JSON format using Python
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 :)
EDITED:
import glob
import json
import io
in0 = input("Enter Userinput0:\n")
in1 = input("Enter Userinput1:\n")
in2 = input("Enter Userinput2:\n")
in3 = input("Enter Userinput3:\n")
name = "somename"
path = "home/fFlder/"
data = defaultdict(list)
for file in glob.iglob(path.join(base_path, "**/"), recursive=True):
data[path.basename(path.dirname(file))]
d = {"Userinput0": in0}
d[name] = {data: {"Userinput1": in1,"Userinput2": in2,"Userinput3": in3, }}
j = json.dumps(d, indent=5)
print (j)
I have tried the above code by traversing the tree. I am getting an error which i mentioned below
**d[name] = {data: {"Userinput1": in1,"Userinput2": in2,"Userinput3": in3, }}
TypeError: unhashable type: 'collections.defaultdict'**
Is am i doing anything wrong here, if so please let me know
Solution 1:[1]
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)
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | TomasO |
| Solution 2 | Sagar Bonde |
