Python 获取目录大小
1. 获取单个文件大小
import os
filesize = os.path.getsize( file_fullpath )
使用 os.path.getsize() 函数,参数是文件的绝对路径
2. 获取文件夹大小
遍历文件夹,将所有文件大小累加,即是该文件夹的大小。
遍历文件夹使用 os.walk() 函数
import os
from os.path import join, getsize
def getdirsize(dir):
size = 0L
for root, dirs, files in os.walk(dir):
size += sum([getsize(join(root, name)) for name in files])
return size
if __name__ == '__main__':
filesize = getdirsize(r'/etc/')
print 'There are %.3f' % (size/1024/1024), 'Mbytes in /etc/'
3. 获取文件夹下特定类型文件的大小
需要通过 os.path.splitext(file) 对文件后缀名进行判断,
例如:统计后缀名为 ['.gz', '.txt', '.conf', '.sh'] 的文件大小
def get_ts_filesize(ts_path, ext_type=['.gz', '.txt', '.conf', '.sh']):
'''
ts_path = /etc
'''
filesize_sum = 0
for root, dirs, files in os.walk(ts_path):
for file in files:
file_ext = os.path.splitext(file)[1]
if file_ext not in ext_type:
continue
file_fullpath = os.path.join(root, file)
filesize = os.path.getsize(file_fullpath)
filesize_sum += filesize
print root, dirs, file, file_ext, file_fullpath, filesize
print filesize_sum
Python 获取目录大小
需要用到的模块:
os, os.path
用到的几个方法:
os.path.exists(strPath) : 判断strPath是否存在。
os.path.isfile(strPath) : 判断strPath 是否是文件
os.walk(strPath) : 遍历strPath.返回一个3元组 根目录,目录列表,文件列表。
os.path.getsize(strPath) : 获取文件的大小
示例代码:
#!/usr/bin/env python
import sys;
import os;
def GetPathSize(strPath):
if not os.path.exists(strPath):
return 0;
if os.path.isfile(strPath):
return os.path.getsize(strPath);
nTotalSize = 0;
for strRoot, lsDir, lsFiles in os.walk(strPath):
#get child directory size
for strDir in lsDir:
nTotalSize = nTotalSize + GetPathSize(os.path.join(strRoot, strDir));
#for child file size
for strFile in lsFiles:
nTotalSize = nTotalSize + os.path.getsize(os.path.join(strRoot, strFile));
return nTotalSize;
if __name__ == '__main__':
nFileSize = GetPathSize(sys.argv[1])
print(nFileSize);
运行结果(单位大小是字节byte):
47678506181
版权所有: 本文系米扑博客原创、转载、摘录,或修订后发表,最后更新于 2015-07-19 05:50:28
侵权处理: 本个人博客,不盈利,若侵犯了您的作品权,请联系博主删除,莫恶意,索钱财,感谢!
转载注明: Python 获取目录大小 (米扑博客)