最新消息:20210917 已从crifan.com换到crifan.org

【已解决】Python中获取文件大小和文件夹大小

Python crifan 4119浏览 0评论

折腾:

【记录】写脚本去加速处理已处理的7.3T数据

期间,需要用Python去获取:

文件的大小

文件夹的整个的大小

python get file folder size

python – Getting File size from user inputed directory – Stack Overflow

How to check size of the files in a directory with python? – Stack Overflow

Getting file size in Python? – Stack Overflow

os.path — Common pathname manipulations — Python 3.7.1 documentation

How to calculate a directory size using Python

Size of a File Folder/Directory (Python) | DaniWeb

Get Directory size in python · GitHub

os — Miscellaneous operating system interfaces — Python 3.7.1 documentation

os — Miscellaneous operating system interfaces — Python 3.7.1 documentation

【总结】

最后用代码:

<code>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


def testNormalFile():
  normalFile = "/Users/mac/working/dev_root/xxx/output/user/3946/show/57589460/show_57589460_video.mp4"
  normalFileSize = getFileFolderSize(normalFile)
  print("normalFileSize=%s" % normalFileSize)

def testFoler():
  # userFolder = "/Users/mac/working/dev_root/xxx/output/user/3946"
  userFolder = "/Users/mac/working/dev_root/xxx/output/course"
  userFolderSize = getFileFolderSize(userFolder)
  print("userFolderSize=%s" % userFolderSize) # userFolderSize=205849009

if __name__ == "__main__":
  # testNormalFile()
  testFoler()
</code>

可以实现:传入file或folder,都可以计算出大小。

注:最新代码已整理至:

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

转载请注明:在路上 » 【已解决】Python中获取文件大小和文件夹大小

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
92 queries in 0.184 seconds, using 23.36MB memory