我正在创建一个实用程序,它将遍历目录并获取所有目录的子目录和文件的大小并存储该值.但是,尺寸计算不正确.
这是我的类,它自动递归所有子目录:
class directory:
'''
Class that automatically traverses directories
and builds a tree with size info
'''
def __init__(self, path, parent=None):
if path[-1] != '/':
# Add trailing /
self.path = path + '/'
else:
self.path = path
self.size = 4096
self.parent = parent
self.children = []
self.errors = []
for i in os.listdir(self.path):
try:
self.size += os.lstat(self.path + i).st_size
if os.path.isdir(self.path + i) and not os.path.islink(self.path + i):
a = directory(self.path + i, self)
self.size += a.size
self.children.append(a) …Run Code Online (Sandbox Code Playgroud) 可以说我的结构是这样的
/-- am here
/one/some/dir
/two
/three/has/many/leaves
/hello/world
Run Code Online (Sandbox Code Playgroud)
并说/ one/some/dir包含一个大文件,500mb和/ three/has/many/leaves在每个文件夹中包含一个400mb文件.
我想生成每个目录的大小,以获得此输出
/ - in total for all
/one/some/dir 500mb
/two 0
/three/has/many/leaved - 400mb
/three/has/many 800
/three/has/ 800+someotherbigfilehere
Run Code Online (Sandbox Code Playgroud)
我该怎么做?