如何获取所有子目录和文件的列表以及它们的大小按大小排序?

2024-06-11 10:41:08 发布

您现在位置:Python中文网/ 问答频道 /正文

如何获取所有子目录和文件的列表以及它们的大小按大小升序排序?在

下面的代码为我提供了所有文件的列表,但没有按大小排序。请帮忙。在

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);

Tags: 文件pathinimport列表fortime排序
1条回答
网友
1楼 · 发布于 2024-06-11 10:41:08
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))

dirs来说也是一样的,尽管我不太确定一个目录的“大小”是多少,但你可能无法用getsize对其进行排序(如果可以,就不会得到有意义的结果)。在

相关问题 更多 >