六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 55|回复: 0

通过python获取目录的大小

[复制链接]

升级  68.2%

265

主题

265

主题

265

主题

进士

Rank: 4

积分
841
 楼主| 发表于 2013-1-15 01:55:13 | 显示全部楼层 |阅读模式
通过python获取目录的大小
 
需要用到的module: os, os.path
import os;
 
 
用到的几个方法:
 
os.path.exists(strPath): 判断strPath是否存在。
os.path.isfile(strPath): 判断strPath 是否是文件
os.walk(strPath):遍历strPath.返回一个3元组 根目录,目录列表,文件列表。
os.path.getsize(strPath): 获取文件的大小
 
PS:源代码

#!/usr/bin/env pythonimport 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); 结果:
47678506181
==> 得到的大小是byte   
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表