Skip to content

Commit 29f7638

Browse files
committed
Update folder_size.py
Made the code more compact by iterating through a dictionary. The line the dictionary and print the file size in Bytes, Kilobytes, Megabytes and Gigabytes.
1 parent 65b13b4 commit 29f7638

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

folder_size.py

+12-10
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,25 @@
11
# Script Name : folder_size.py
22
# Author : Craig Richards
33
# Created : 19th July 2012
4-
# Last Modified : 14 February 2016
4+
# Last Modified : 22 February 2016
55
# Version : 1.0.1
66

7-
# Modifications : 1.0.1 - Tidy up comments and syntax, add main() function
7+
# Modifications : Modified the Printing method and added a few comments
88

99
# Description : This will scan the current directory and all subdirectories and display the size.
1010

1111
import os # Load the library module
12-
1312
directory = '.' # Set the variable directory to be the current directory
1413
dir_size = 0 # Set the size to 0
1514

16-
for (path, dirs, files) in os.walk(directory): # Walk through all the directories
15+
fsizedicr = {'Bytes': 1, 'Kilobytes': float(1)/1024, 'Megabytes': float(1)/(1024*1024), 'Gigabytes': float(1)/(1024*1024
16+
*
17+
1024)}
18+
19+
for (path, dirs, files) in os.walk(directory): # Walk through all the directories. For each iteration, os.walk returns the folders, subfolders and files in the dir.
1720
for file in files: # Get all the files
18-
filename = os.path.join(path, file)
19-
dir_size += os.path.getsize(filename) # Get the sizes, the following lines print the sizes in bytes, Kb, Mb and Gb
20-
print "Folder Size in Bytes = %0.2f Bytes" % (dir_size)
21-
print "Folder Size in Kilobytes = %0.2f KB" % (dir_size/1024.0)
22-
print "Folder Size in Megabytes = %0.2f MB" % (dir_size/1024/1024.0)
23-
print "Folder Size in Gigabytes = %0.2f GB" % (dir_size/1024/1024/1024.0)
21+
filename = os.path.join(path, file)
22+
dir_size += os.path.getsize(filename) # Add the size of each file in the root dir to get the total size.
23+
24+
for key in fsizedicr: #iterating through the dictionary
25+
print ("Folder Size: " + str(round(fsizedicr[key]*dir_size, 2)) + " " + key) # round function example: round(4.2384, 2) ==> 4.23

0 commit comments

Comments
 (0)