简体   繁体   中英

How to get list of all sub directories and files along with their size ordered by size?

How to get list of all sub directories and files along with their size ordered by size in ascending order?

The below code gets me the list of all files, but is not sorted according to 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);
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 thing for dirs -- Although I'm not really sure what the "size" of a directory actually is -- You probably can't sort that one with getsize (and if you can, you won't get a result that is meaningful).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM