如何分别使用Python获取每个子文件夹的大小?
问题描述:
我与分成3子文件夹(A,LYR,出)一个大的目录(项目)工作,他们分为子子文件夹中有很多的文件里面他们:如何分别使用Python获取每个子文件夹的大小?
我尝试分别获取这3个子文件夹的大小 - 每个子文件夹。当我使用此代码(我红Calculating a directory size using Python?):
import os
def get_size(start_path = "."):
total_size = 0
for dirpath, dirnames, filenames in os.walk(start_path):
for f in filenames:
fp = os.path.join(dirpath, f)
total_size += os.path.getsize(fp)
return total_size
path = r"G:\desktop\Project"
dirList = os.listdir(path)
for fname in dirList:
print fname
print get_size(path)
我得到:
>>>
a
41730716
lyr
41730716
out
41730716
>>>
我不明白什么是我的错误。
41730716是所有的“工程”目录的大小,而这不是我想要的。我需要子文件夹的大小:a,lyr,每个。 其实,子文件夹的大小为23.4 MB,LYR为12 MB,出门就是4 MB-那些我需要的结果得到的值。
我红: 在Calculating size folder python。在这个问题中,我只获得了包括所有子文件夹大小的目录大小 - 这不是我所需要的。
答
最后,我用这个代码:
import os
def get_size(start_path = "."):
total_size = 0
for dirpath, dirnames, filenames in os.walk(start_path):
for f in filenames:
fp = os.path.join(dirpath, f)
total_size += os.path.getsize(fp)
return "Folder = %0.1f MB" % (total_size/(1024*1024.0))
os.chdir(r"G:\desktop\Project")
all_subdirs = [ d for d in os.listdir('.') if os.path.isdir(d)]
for dirs in all_subdirs:
dir = os.path.join(r"G:\desktop\Project", dirs)
os.chdir(dir)
current = os.getcwd()
print current
print get_size(current)