You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

30 lines
989 B

  1. import os
  2. from math import log
  3. def sizeof_fmt(num):
  4. """Human friendly file size"""
  5. unit_list = zip(['bytes', 'kiB', 'MiB', 'GiB', 'TiB'], [0, 0, 1, 2, 2])
  6. if num > 1:
  7. exponent = min(int(log(num, 1024)), len(unit_list) - 1)
  8. quotient = float(num) / 1024**exponent
  9. unit, num_decimals = unit_list[exponent]
  10. format_string = '{:.%sf} {}' % (num_decimals)
  11. return format_string.format(quotient, unit)
  12. if num == 0: # pragma: no cover
  13. return '0 bytes'
  14. if num == 1: # pragma: no cover
  15. return '1 byte'
  16. def du_bytes(path):
  17. """Like du -sb, returns total size of path in bytes."""
  18. size = os.path.getsize(path)
  19. if os.path.isdir(path):
  20. for thisfile in os.listdir(path):
  21. filepath = os.path.join(path, thisfile)
  22. size += du_bytes(filepath)
  23. return size
  24. def du(path):
  25. """Like du -sh, returns total size of path as a human-readable string."""
  26. return sizeof_fmt(du_bytes(path))