前言:
Linux系统命令"du -s"获取文件夹大小的速度最快,而且不限文件夹嵌套深度。 基于Python脚本调用这一命令,即可实现文件夹大小输出,同时避免了遍历循环低效。 经测试,程序在 Python2.7 和 Python3.6 环境下都能成功运行。
程序:
#!/usr/bin/env python
# --coding:utf-8--
import os
import subprocess
import re
# 待测目录
Dir = '/home'
# 大小转换函数
def Covert_File_Size(size):
kb = 1;
mb = kb * 1024;
gb = mb * 1024;
tb = gb * 1024;
if size >= tb:
return "%.2f TB" % float(size / tb)
if size >= gb:
return "%.2f GB" % float(size / gb)
if size >= mb:
return "%.2f MB" % float(size / mb)
if size >= kb:
return "%.2f KB" % float(size / kb)
if size < kb:
return "%.2f Byte" % float(size)
# 定义文件夹大小获取函数
def getFoldersize(path):
'''
计算当前文件夹下所有文件大小
返回文件夹大小以KB为单位
'''
return_number = 0
if os.path.exists(path):
output = subprocess.check_output(["du","-s",path])
subprocess_output = output.decode("utf-8")
searchObj = re.match( r'^\s*([0-9]+)', subprocess_output, re.M|re.I)
if searchObj:
Str_number = searchObj.group()
else:
Str_number = 0
if float(Str_number) |