cho.sh Finding the size of the directory in Python · cho.sh
Finding the size of the directory in Python
Finding the size of the directory in Python
Warning
This post is more than a year old. Information may be outdated.
=
False
, shortRead
=
False
):
size = 0
sizeArr = []
units = ["B", "KB", "MB", "GB", "TB", "PB", "EB"]
if os.path.isdir(path):
for dirpath, dirnames, filenames in os.walk(path):
for i in filenames:
size += os.path.getsize(os.path.join(dirpath, i))
elif os.path.isfile(path):
size += os.path.getsize(path)
unit = math.floor(math.log(size, kilo))
for k in range(0, unit + 1):
sizeArr.append(
math.floor((size % kilo ** (k + 1)) / kilo ** k)
)
if readable:
sizeString = ""
if not shortRead:
for x in range(unit, -1, -1):
sizeString += str(sizeArr[x]) + units[x] + " "
return sizeString[:-1]
else:
return (
str(sizeArr[-1])
+ "."
+ str(math.floor(sizeArr[-2] / 1.024))
+ units[len(sizeArr) - 1]
)
else:
return sizeArr
Examples
Reference
C:\Users\anacl\OneDrive\Documents (Folder): 3.13GB (3,366,343,239 Bytes)
C:\Users\anacl\OneDrive\Pictures (Folder): 83.4MB (87,468,781 Bytes)
C:\Users\anacl\OneDrive\Pictures\screenshot.png (File): 139KB (143,262 Bytes)
Default
Each element in the returned list is the value of [B, KB, MB, GB, ...] of the file size.
Full Readable Output
Short Readable Output
No comments yet. Be the first to share your thoughts.