So I’m just hitting a mental roadblock on solving this problem and none of the other questions I have looked at have really captured my particular use-case. One was close but I couldn’t quite figure out how to tailor it specifically. Basically, I have a script that uses os.walk()
and renames any files within a target directory (and any sub-directories) according to user-defined rules. The specific problem is that I am trying to log the results of the operation in JSON format with an output like this:
{
"timestamp": "2022-12-26 09:40:55.874718",
"files_inspected": 512,
"files_renamed": 256,
"replacement_rules": {
"%20": "_",
" ": "_"
},
"target_path": "/home/example-user/example-folder",
"data": [
{
"directory": "/home/example-user/example-folder",
"files": [
{
"original_name": "file 1.txt",
"new_name": "file_1.txt"
},
{
"original_name": "file 2.txt",
"new_name": "file_2.txt"
},
{
"original_name": "file 3.txt",
"new_name": "file_3.txt"
}
],
"children": [
{
"directory": "/home/example-user/example-folder/sub-folder",
"files": [
{
"original_name": "file 1.txt",
"new_name": "file_1.txt"
},
{
"original_name": "file 2.txt",
"new_name": "file_2.txt"
},
{
"original_name": "file 3.txt",
"new_name": "file_3.txt"
}
]
}
]
}
]
}
The first item in the 3-tuple (dirpath
) begins as the target directory, and on that same loop the second item in the 3-tuple (dirnames
) is a list of the directories within that dirpath
(if any). However, what I think is messing me up is that on the second loop, dirpath
becomes the first item in dirnames
in the prior loop (if there were any). I am having trouble working out the logic of transforming this 3-tuple loop data into the nested hierarchy above. Ideally, it would be nice if a directory object which had no sub-directories (children
) would also not have the children
key at all, but having it set to an empty list would be fine.
I would really appreciate any advice or insight you might have on how to achieve that desired log structure from what os.walk()
provides. Also open to any suggestions on improving the JSON object structure. Thank you!
2
Answers
I am not totally sure if I got your request right. But to get a simple nested structure from
os.walk
you could try the following:yields an output like
Does this help?
Note: this is a minimal example, trying to solve the main part of the request.
You need to build the rest of your structure around it.
Note 2: The key
files
might cause a conflict if you have a subfolder namesfiles
somewhere. Choose wisely. 😉One issue in your approach is that you want a hierarchical result that is most naturally obtained by recursion, whereas
os.walk
flattens that hierarchy.For this reason, I would recommend using
os.scandir
instead. It also happens to be one of the most performant tools to interact with a directory tree.Example
Let’s build a reproducible example:
Now, using the
rename()
function above: