Skip to content

Instantly share code, notes, and snippets.

@SteveClement
Created September 20, 2012 12:18
Show Gist options
  • Save SteveClement/3755572 to your computer and use it in GitHub Desktop.
Save SteveClement/3755572 to your computer and use it in GitHub Desktop.
Get Directory size in python
import os
def get_size(start_path = '.'):
total_size = 0
for dirpath, dirnames, filenames in os.walk(start_path):
for f in filenames:
fp = os.path.join(dirpath, f)
total_size += os.path.getsize(fp)
return total_size
print get_size()
@kathysll
Copy link

kathysll commented Feb 8, 2019

import os

total_size = 0
start_path = r"G:\USLAHAM1901"
#get size of current directory
for path, dirs, files in os.walk(start_path):
for f in files:
fp = os.path.join(path,f)
total_size += os.path.getsize(fp)
print("Drictory size:" + str(total_size))

how to translate the result from a huge number to GB or TB? Thank you very much.

@dmavlov
Copy link

dmavlov commented Feb 21, 2019

...
print('Drictory size: {:,} bytes'.format(total_size).replace(',', ' '))
print('Drictory size: {:,} KB'.format(int(total_size/1024)).replace(',', ' '))
print('Drictory size: {:,} MB'.format(int(total_size/1024**2)).replace(',', ' '))
print('Drictory size: {:,} GB'.format(int(total_size/1024**3)).replace(',', ' '))
print('Drictory size: {:,} TB'.format(int(total_size/1024**4)).replace(',', ' '))

example result

Drictory size: 126 291 748 492 bytes
Drictory size: 123 331 785 KB
Drictory size: 120 441 MB
Drictory size: 117 GB
Drictory size: 0 TB

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment