栈实现
def get_dir_size(path):
size = 0
dirlist = []
if os.path.isdir(path): # 判断path是否为文件夹
dirlist.append(path) # 追加文件夹路径到dirlist列表中
while dirlist: # 如果dirlist非空就进行循环计算文件大小
now_dirname = dirlist.pop() # 取出目录路径
now_dir_list = os.listdir(now_dirname) # 取出目录内的所有文件
for name in now_dir_list: # 循环目录内的所有文件判断类型
name = os.path.join(now_dirname, name) # 对文件进行路径拼接
if os.path.isdir(name): # 如果是目录就把路径追加到dirlist
dirlist.append(name)
else: # 如果不是目录就进行计算大小
size += os.path.getsize(name)
elif os.path.isfile(path):
size = os.path.getsize(path)
return size
res = get_dir_size(path=path)
print(res)
递归函数实现
def get_dir_size(path):
size = 0
if os.path.isdir(path):
allfile = os.listdir(path)
for name in allfile:
name = os.path.join(path, name)
if os.path.isdir(name):
size += get_dir_size(name)
else:
size += os.path.getsize(name)
elif os.path.isfile(path):
size = os.path.getsize(path)
else:
return None
return size
res = get_dir_size(path)
print(res)