Python计算磁盘使用量的1000倍du

2024-09-19 23:30:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我按照说明计算磁盘使用率:

import os
def disk_usage(path):
  """Return the number of bytes used by a file/folder and any descendents."""
  total = os.path.getsize(path)                  # account for direct usage
  if os.path.isdir(path):                        # if this is a directory,
    for filename in os.listdir(path):            # then for each child:
      childpath = os.path.join(path, filename)   # compose full path to child
      total += disk_usage(childpath)             # add child's usage to total

  print ('{0:<10}'.format(total), path)           # descriptive output (optional)
  return total                                   # return the grand total

运行它并获取:

disk_usage("/Users/me/Desktop/PubRepo")    

117976604  /Users/me/Desktop/PubRepo
Out[117]: 117976604

然而,当我使用du

In [124]: !du -s /Users/me/Desktop/PubRepo                                                                  
125900  /Users/me/Desktop/PubRepo

   -s, --summarize
          display only a total for each argument



In [1]: 117976604 / 125900                                                                                      
Out[1]: 937.0659571088165

python的结果大约是1000倍

可能有什么问题


Tags: thepathchildforifosusagefilename