【转载】python获取文件及文件夹大小

来源:互联网 发布:淘宝买家钻号 编辑:程序博客网 时间:2024/06/11 18:27

使用os.path.getsize函数,参数是文件的路径。

获取文件夹大小,即遍历文件夹,将所有文件大小加和。遍历文件夹使用os.walk函数

import osfrom os.path import join, getsizedef getdirsize(dir):   size = 0L   for root, dirs, files in os.walk(dir):      size += sum([getsize(join(root, name)) for name in files])   return sizeif '__name__' == '__main__':   filesize = getdirsize(r'c:\windows')   print 'There are %.3f' % (size/1024/1024), 'Mbytes in c:\\windows'

源自:http://blog.csdn.net/cashey1991/article/details/


分隔符

刚才遇到了这个问题,比如我只想要一个文件夹中所有的’.tmp’后缀的文件,那么代码改成:

import osfrom os.path import join, getsizedef getdirsize(dir):   size = 0L   for root, dirs, files in os.walk(dir):      size += sum([getsize(join(root, name)) for name in files if os.path.splitext(name)[1] =='.tmp'])   return sizeif '__name__' == '__main__':   filesize = getdirsize(r'c:\windows')   print 'There are %.3f' % (size/1024/1024), 'Mbytes in c:\\windows'
1 0
原创粉丝点击