这是 Python(2.7 兼容语法)脚本:
import sys
from os import stat, getcwd
from os.path import isdir, isfile, join
from glob import glob
from pprint import pprint
NAME_KEY = "name"
SIZE_KEY = "size"
CHILDREN_KEY = "children"
def _iter_path_w_files(path):
if isfile(path):
return {NAME_KEY: path, SIZE_KEY: stat(path).st_size}
elif isdir(path):
ret = {NAME_KEY: path, CHILDREN_KEY: []}
for child in glob(join(path, "*")):
ret[CHILDREN_KEY].append(_iter_path_w_files(child))
return ret
else: # For readability only
return None
def _iter_path_wo_files(path):
ret = {NAME_KEY: path, SIZE_KEY: 0}
for child in glob(join(path, "*")):
if isfile(child):
ret[SIZE_KEY] += stat(child).st_size
else:
child_ret = _iter_path_wo_files(child)
ret.setdefault(CHILDREN_KEY, []).append(child_ret)
ret[SIZE_KEY] += child_ret[SIZE_KEY]
return ret
def iter_path(path, show_files=True):
if show_files:
return _iter_path_w_files(path)
else:
if isfile(path):
return stat(path).st_size
elif isdir(path):
return _iter_path_wo_files(path)
else: # For readability only
return None
if __name__ == "__main__":
if len(sys.argv) > 1:
path = sys.argv[1]
else:
path = getcwd()
files = False # Toggle this var if you want the files reported or not
d = iter_path(path, files)
pprint(d)
对于像这样的目录树(文件旁边的数字是它们的大小):
输出将是:
files = False
:
{'children': [
{'children': [
{'children': [
{'name': 'dir0\\dir00\\dir000\\dir0000',
'size': 9L
}
],
'name': 'dir0\\dir00\\dir000',
'size': 9L
}
],
'name': 'dir0\\dir00',
'size': 16L
},
{'children': [
{'name': 'dir0\\dir01\\dir010',
'size': 0
}
],
'name': 'dir0\\dir01',
'size': 7L
}
],
'name': 'dir0',
'size': 29L
}
files = True
:
{'name': 'dir0',
'children': [
{'name': 'dir0\\dir00',
'children': [
{'name': 'dir0\\dir00\\dir000',
'children': [
{'name': 'dir0\\dir00\\dir000\\dir0000',
'children': [
{'name': 'dir0\\dir00\\dir000\\dir0000\\file00000',
'size': 9L
}
]
}
]
},
{'name': 'dir0\\dir00\\file000',
'size': 7L
}
]
},
{'name': 'dir0\\dir01',
'children': [
{'name': 'dir0\\dir01\\dir010',
'children': []
},
{'name': 'dir0\\dir01\\file010',
'size': 7L
}
]
},
{'name': 'dir0\\file00',
'size': 6L
}
]
}
这些是与 json 完全兼容的 python 字典(我对其进行了格式化以提高可读性)(您可以尝试:(字典json.dumps(d)
在哪里d
))。