Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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()
@njuguoyi

This comment has been minimized.

Copy link

commented Dec 20, 2017

total_size += (os.path.getsize(fp) if os.path.isfile(fp) else 0)

@kapsh

This comment has been minimized.

Copy link

commented Feb 7, 2018

@njuguoyi there will be only files in fp - os.walk returns them separatedly from directories.

@kathysll

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.