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)

 

你可能感兴趣的:(python)