How to get a list of all subdirectories and files along with their size sorted by size?

How to get a list of all subdirectories and files along with their size, sorted by size in ascending order?

Below is the code for all the files, but not sorted by size. Please, help.

import os import os.path, time from os.path import join, getsize count=0 for root, dirs, files in os.walk('Test'): for file in list(files): fileaddress = os.path.join(root, file) print("\nName:",fileaddress) print("Time:",time.strftime("%m/%d/%Y %I:%M:%S %p",time.localtime(os.path.getmtime(fileaddress)))) count=count+1 print(count); 
+4
source share
1 answer
 import os from os.path import join, getsize file_list = [] for root, dirs, files in os.walk('Test'): file_list.extend( join(root,f) for f in files ) #May be *slightly* faster at the expense of a little readability # and a little memory # file_list.extend( [ join(root,f) for f in files ] ) print (sorted(file_list, key=getsize)) 

And the same goes for dirs - Although I'm not quite sure what the "size" of the directory really is - you probably can't sort it with getsize (and if you can, you won't get a result that makes sense).

+5
source

Source: https://habr.com/ru/post/1444951/


All Articles