Skip to content

Instantly share code, notes, and snippets.

@anaclumos
Created April 16, 2020 16:35
Show Gist options
  • Save anaclumos/31e3ff08a4d302c2778764c569b2b168 to your computer and use it in GitHub Desktop.
Save anaclumos/31e3ff08a4d302c2778764c569b2b168 to your computer and use it in GitHub Desktop.
Get Python File Size in Readable Format
def size(path, kilo=1000):
total_size = 0
for dirpath, dirnames, filenames in os.walk(path):
for i in filenames:
f = os.path.join(dirpath, i)
total_size += os.path.getsize(f)
if total_size < kilo:
return str(total_size)
elif total_size < kilo ** 2:
return str(int(total_size / kilo)) + "KB " + str(int(total_size % kilo)) + "B"
elif total_size < kilo ** 3:
return (
str(int(total_size / kilo ** 2))
+ "MB "
+ str(int((total_size % kilo ** 2) / kilo))
+ "KB "
+ str(int(total_size % kilo))
+ "B"
)
else:
return (
str(int(total_size / kilo ** 3))
+ "GB "
+ str(int((total_size % kilo ** 3) / kilo ** 2))
+ "MB "
+ str(int((total_size % kilo ** 2) / kilo))
+ "KB "
+ str(int(total_size % kilo))
+ "B"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment