# 计算文件夹里所有内容的大小总和

## 递归方法

'''计算文件夹的大小'''
import os
def dir_file_size(path):
if os.path.isdir(path):
file_size = 0
dir_list = os.listdir(path)
for dir_name in dir_list:
file_path = os.path.join(path,dir_name)
if os.path.isfile(dir_name):
file_size += os.path.getsize(file_path)
else:
ret = dir_file_size(file_path)
file_size += ret
return file_size
elif os.path.isfile(path):
return os.path.getsize(path)
else:print('找不到%s文件'%path)

path = r'D:\oldbaoy_python_project\day04'
ret = dir_file_size(path)
print('{0} 的大小为 {1}字节'.format(path,ret))

## 栈方法

import os

def dir_file_size(path):
if os.path.isdir(path):
file_size, dir_list = 0, [path]
while dir_list:
path = dir_list.pop()
dirs = os.listdir(path)
for name in dirs:
file_path = os.path.join(path, name)
if os.path.isfile(file_path):
file_size += os.path.getsize(file_path)
else:
dir_list.append(file_path)
return file_size
elif os.path.isfile(path):
return os.path.getsize(path)
else:
print('找不到%s文件' % path)

path = r'D:\oldbaoy_python_project\day04'
ret = dir_file_size(path)
print('{0} 的大小为 {1}字节'.format(path, ret))

QQ号联系： 360901061

【本文对您有帮助就好】