[英]How can I create a folder tree in json format using python?
I am wondering, if it possible, to provide a folder path and let a python script scan the given folder and return a json tree with the amount of files for each folder.我想知道,如果可能的话,提供一个文件夹路径并让 python 脚本扫描给定的文件夹并返回一个 json 树,其中包含每个文件夹的文件数量。 The tree should contain every sub-folder:
树应包含每个子文件夹:
Eg result:例如结果:
[{
foldername: "folder1",
amount_of_files: 123,
children: [
{
foldername: "folder1.1",
amount_of_files: 3,
children: []
},
{
foldername: "folder1.2",
amount_of_files: 5,
children: [
{
foldername: "folder1.2.1",
amount_of_files: 20,
children: []
}
]
}
]
},
{
foldername: "folder2",
amount_of_files: 1,
children: [
{
foldername: "folder2.1",
amount_of_files: 3,
children: [
{
foldername: "folder2.1.1",
amount_of_files: 2,
children: [
{
foldername: "folder2.1.1.1",
amount_of_files: 24,
children: []
}
]
}
]
},
{
foldername: "folder1.2",
amount_of_files: 5,
children: []
}
]
}
]
You can use os.listdir
with recursion:您可以将
os.listdir
与递归一起使用:
import os, json
def get_tree(path=os.getcwd()):
return {'foldername':path,
'amount_of_files':sum(not os.path.isdir(os.path.join(path, k)) for k in os.listdir(path)),
'children':[get_tree(os.path.join(path, k)) for k in os.listdir(path) if os.path.isdir(os.path.join(path, k))]}
with open('folder_tree.json', 'w') as f:
json.dump(get_tree(), f)
To produce a list of dictionaries, with each dictionary containing the folder name and number of files, you can use a recursive generator function:要生成字典列表,每个字典包含文件夹名称和文件数,您可以使用递归生成器 function:
def get_tree(path=os.getcwd()):
yield {'foldername':path, 'amount_of_files':sum(not os.path.isdir(os.path.join(path, k)) for k in os.listdir(path))}
for i in os.listdir(path):
if os.path.isdir(os.path.join(path, i)):
yield from get_tree(os.path.join(path, i))
with open('folder_tree.json', 'w') as f:
json.dump(list(get_tree()), f)
This seems to do the job:这似乎可以完成这项工作:
from os import listdir
from os.path import isdir, isfile, basename, join
from json import dumps
def folder(d):
result = dict(
amount_of_files=0,
foldername=basename(d)
)
for each in listdir(d):
path = join(d, each)
if isdir(path):
if 'children' not in result:
result['children'] = list()
result['children'].append(folder(path))
if isfile(path):
result['amount_of_files'] += 1
return result
print(dumps(folder('.')))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.