python 获取文件夹大小

注意,这里是属性里的文件大小。而不是占用空间。实际占用空间会>文件大小。

 

想获取占用空间貌似需要用到shell,暂时没有深入研究。

 

1.获取文件大小的方法

 

1.1 os.path.getsize()

最简单无脑常用,返回Byte为单位的大小。

import os

path='/hha/dd.k' 
sz = os.path.getsize(path)

print(sz)

 

1.2  fileobj.tell()

import os

def getSize(fileobject):
    fileobject.seek(0,2) # move the cursor to the end of the file
    size = fileobject.tell()
    return size

file = open('myfile.bin', 'rb')
print getSize(file)

 

1.3 os.stat().st_size

import os

path = '/aaa/bbb.ccc'

sz = os.stat(path).st_size 

 

2.获取文件夹大小的方法

其实就是遍历整个文件夹的所有子文件,然后加总getsize的返回值。

所以核心就是如何遍历

 

2.1 os.scandir()

 

#直接找了现成的轮子。不过我不喜欢驼峰命名啊看着好累。

import os

def getFileFolderSize(fileOrFolderPath):
  """get size for file or folder"""
  totalSize = 0

  if not os.path.exists(fileOrFolderPath):
    return totalSize
  
  if os.path.isfile(fileOrFolderPath):
    totalSize = os.path.getsize(fileOrFolderPath) # 5041481
    return totalSize

  if os.path.isdir(fileOrFolderPath):
    with os.scandir(fileOrFolderPath) as dirEntryList:
      for curSubEntry in dirEntryList:
        curSubEntryFullPath = os.path.join(fileOrFolderPath, curSubEntry.name)
        if curSubEntry.is_dir():
          curSubFolderSize = getFileFolderSize(curSubEntryFullPath) # 5800007
          totalSize += curSubFolderSize
        elif curSubEntry.is_file():
          curSubFileSize = os.path.getsize(curSubEntryFullPath) # 1891
          totalSize += curSubFileSize

      return totalSize


normalFile ="/aaa/bbb.ccc"
normalFileSize = getFileFolderSize(normalFile)
print("normalFileSize=%s" % normalFileSize)


userFolder = "/aaa/ddd/"
userFolderSize = getFileFolderSize(userFolder)
print("userFolderSize=%s" % userFolderSize) 



#source:https://github.com/crifan/crifanLibPython/blob/master/crifanLib/crifanFile.py

 

 

2.2 os.walk()

 

def getdirsize(dir):
   size = 0
   for root, dirs, files in os.walk(dir):
      size += sum([getsize(join(root, name)) for name in files])
   return size

dirpath = '/aaa/bbb/'
sz = getdirsize(dirpath)
print(sz)

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值