为了方便统计目录大小,写了2个函数,一个用来统计目录大小,单位是字节;连一个将大小,转成可视化的单位,比如2.1GB。
python
import os
def get_dir_size(dir_path):
"""
统计目录大小
:param dir_path: 目录名
:return: int 目录大小
"""
if not os.path.isdir(dir_path):
print('%s 不是个目录!' % dir_path)
return
files = os.listdir(dir_path)
# print(files)
total_size = 0
for file in files:
# print(image)
file_path = os.path.join(dir_path, file)
total_size += os.path.getsize(file_path)
# print(total_size)
return total_size
def change_size_to_text(total_size):
"""
将字节转为可视化的文本
:param total_size: int
:return: text
"""
gb_size = 1.0 * 1024 * 1024 * 1024
mb_size = 1.0 * 1024 * 1024
kb_size = 1.0 * 1024
if total_size <= kb_size:
total_size_format = '%.2f B' % round(total_size, 2)
elif total_size <= mb_size:
total_size_format = '%.2f KB' % round(total_size / kb_size, 2)
elif total_size <= gb_size:
total_size_format = '%.2f MB' % round(total_size / mb_size, 2)
elif total_size > gb_size:
total_size_format = '%.2f GB' % round(total_size / gb_size, 2)
return total_size_format
if __name__ == '__main__':
dirpath = './test-dir/'
print(get_dir_size(dirpath ))
print(change_size_to_text(get_dir_size(dirpath )))