Skip to content

Instantly share code, notes, and snippets.

@amenayach
Created October 11, 2022 23:46
Show Gist options
  • Save amenayach/0d9ad0b916e2db08c8a4686e37bbbd2e to your computer and use it in GitHub Desktop.
Save amenayach/0d9ad0b916e2db08c8a4686e37bbbd2e to your computer and use it in GitHub Desktop.
A python script that sort a folder content considering not only files but folders.
import os,sys,time
def get_size(start_path = '.'):
total_size = 0
for dirpath, _, filenames in os.walk(start_path):
for file in filenames:
file_path = os.path.join(dirpath, file)
total_size += os.path.getsize(file_path)
return total_size
if __name__ == '__main__':
root_dir = '.'
if len(sys.argv) > 1:
root_dir = sys.argv[1]
now = time.time()
result = []
dirs = os.listdir(root_dir)
dir_len = len(dirs)
count = 0
for name in dirs:
if len(sys.argv) > 2 and sys.argv[2] == '-v':
count += 1
percentage = '{0:0=.2f}'.format(count*100/dir_len)
s = ('\r%s%% >> Processing: %s' % (percentage, name)).ljust(128)
print(s, end='\r')
if os.path.isdir(os.path.join(root_dir, name)):
result.append((name, get_size(os.path.join(root_dir, name))))
else:
result.append((name, os.path.getsize(os.path.join(root_dir, name))))
result.sort(key=lambda x: x[1], reverse=True)
for entry in result:
size = '{:,}'.format(entry[1])
mb = '{0:0=.3f}'.format(entry[1]/(1048576))
print('%s\t%sMB (%s bytes)' % (entry[0].ljust(60), mb, size))
total_bytes = sum([x[1] for x in result])
total_mb = '{0:0=.3f}'.format(total_bytes/(1048576))
total_size = '{:,}'.format(total_bytes)
print('-' * 100)
print('Total size: %sMB (%s bytes)' % (total_mb, total_size))
print('Total time: %fs' % (time.time() - now))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment