Chinaunix首页 | 论坛 | 博客
  • 博客访问: 360612
  • 博文数量: 150
  • 博客积分: 3423
  • 博客等级: 中校
  • 技术积分: 1005
  • 用 户 组: 普通用户
  • 注册时间: 2011-07-15 09:04
文章分类

全部博文(150)

文章存档

2012年(2)

2011年(148)

分类: Python/Ruby

2011-09-09 21:38:12

 

需要用到的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): 获取文件的大小


  1. #!/usr/bin/env python
  2. import sys;
  3. import os;

  4. def GetPathSize(strPath):
  5.     if not os.path.exists(strPath):
  6.         return 0;

  7.     if os.path.isfile(strPath):
  8.         return os.path.getsize(strPath);

  9.     nTotalSize = 0;
  10.     for strRoot, lsDir, lsFiles in os.walk(strPath):
  11.         #get child directory size
  12.         for strDir in lsDir:
  13.             nTotalSize = nTotalSize + GetPathSize(os.path.join(strRoot, strDir));

  14.         #for child file size
  15.         for strFile in lsFiles:
  16.             nTotalSize = nTotalSize + os.path.getsize(os.path.join(strRoot, strFile));

  17.     return nTotalSize;

  18. if __name__ == '__main__':
  19.     nFileSize = GetPathSize(sys.argv[1])
  20.     print(nFileSize);

   

结果:

47678506181 (byte)

阅读(814) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~