Skip to content

Commit 799a0a7

Browse files
committed
added directory size tutorial
1 parent 35df40e commit 799a0a7

File tree

4 files changed

+77
-0
lines changed

4 files changed

+77
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ This is a repository of all the tutorials of [The Python Code](https://www.thepy
5656
- [How to Automate your VPS or Dedicated Server Management in Python](https://www.thepythoncode.com/article/automate-veesp-server-management-in-python). ([code](general/automating-server-management))
5757
- [How to Execute BASH Commands in a Remote Machine in Python](https://www.thepythoncode.com/article/executing-bash-commands-remotely-in-python). ([code](general/execute-ssh-commands))
5858
- [How to Convert Python Files into Executables](https://www.thepythoncode.com/article/building-python-files-into-stand-alone-executables-using-pyinstaller)
59+
- [How to Get the Size of Directories in Python](https://www.thepythoncode.com/article/get-directory-size-in-bytes-using-python). ([code](general/calculate-directory-size))
5960

6061
- ### [Web Scraping](https://www.thepythoncode.com/topic/web-scraping)
6162
- [How to Access Wikipedia in Python](https://www.thepythoncode.com/article/access-wikipedia-python). ([code](web-scraping/wikipedia-extractor))
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# [How to Get the Size of Directories in Python](https://www.thepythoncode.com/article/get-directory-size-in-bytes-using-python)
2+
To run this:
3+
- `pip3 install -r requirements.txt`
4+
- To get the size of subdirectories of `/root/home` directory:
5+
```
6+
python get_directory_size.py /root/home
7+
```
8+
This will show a pie chart that indicates the size of each subdirectory.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import os
2+
import matplotlib.pyplot as plt
3+
4+
5+
def get_size_format(b, factor=1024, suffix="B"):
6+
"""
7+
Scale bytes to its proper byte format
8+
e.g:
9+
1253656 => '1.20MB'
10+
1253656678 => '1.17GB'
11+
"""
12+
for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]:
13+
if b < factor:
14+
return f"{b:.2f}{unit}{suffix}"
15+
b /= factor
16+
return f"{b:.2f}Y{suffix}"
17+
18+
19+
def get_directory_size(directory):
20+
"""Returns the `directory` size in bytes."""
21+
total = 0
22+
try:
23+
# print("[+] Getting the size of", directory)
24+
for entry in os.scandir(directory):
25+
if entry.is_file():
26+
# if it's a file, use stat() function
27+
total += entry.stat().st_size
28+
elif entry.is_dir():
29+
# if it's a directory, recursively call this function
30+
total += get_directory_size(entry.path)
31+
except NotADirectoryError:
32+
# if `directory` isn't a directory, get the file size then
33+
return os.path.getsize(directory)
34+
except PermissionError:
35+
# if for whatever reason we can't open the folder, return 0
36+
return 0
37+
return total
38+
39+
40+
def plot_pie(sizes, names):
41+
"""Plots a pie where `sizes` is the wedge sizes and `names` """
42+
plt.pie(sizes, labels=names, autopct=lambda pct: f"{pct:.2f}%")
43+
plt.title("Different Sub-directory sizes in bytes")
44+
plt.show()
45+
46+
47+
if __name__ == "__main__":
48+
import sys
49+
folder_path = sys.argv[1]
50+
51+
directory_sizes = []
52+
names = []
53+
# iterate over all the directories inside this path
54+
for directory in os.listdir(folder_path):
55+
directory = os.path.join(folder_path, directory)
56+
# get the size of this directory (folder)
57+
directory_size = get_directory_size(directory)
58+
if directory_size == 0:
59+
continue
60+
directory_sizes.append(directory_size)
61+
names.append(os.path.basename(directory) + ": " + get_size_format(directory_size))
62+
63+
print("[+] Total directory size:", get_size_format(sum(directory_sizes)))
64+
plot_pie(directory_sizes, names)
65+
66+
67+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
matplotlib

0 commit comments

Comments
 (0)