I want to use Python to list a directory, then sort the filenames by size
The following gets the files, but they are not sorted.
for fn in os.listdir(path):
if fn[0] == '.':
co开发者_如何学编程ntinue
try:
p = os.path.join(path, fn)
except:
continue
s = os.lstat(p)
if stat.S_ISDIR(s.st_mode):
l.append((fn, build_tree(p)))
elif stat.S_ISREG(s.st_mode):
l.append((fn, s.st_size))
A way
>>> import operator
>>> import os
>>> getall = [ [files, os.path.getsize(files)] for files in os.listdir(".") ]
>>> sorted(getall, key=operator.itemgetter(1))
Using sorted is the most efficient and standard way.
ascending:
sorted_list = sorted(files, key=os.path.getsize)
descending
sorted_list = sorted(files, key=os.path.getsize, reverse=True)
import operator
for fn in os.listdir(path):
if fn[0] == '.':
continue
try:
p = os.path.join(path, fn)
except:
continue
s = os.lstat(p)
if stat.S_ISDIR(s.st_mode):
l.append((fn, build_tree(p)))
elif stat.S_ISREG(s.st_mode):
l.append((fn, s.st_size))
For ascending sort:
l.sort(key=operator.itemgetter(1))
For descending sort:
l.sort(key=operator.itemgetter(1), reverse=True)
Maybe this will give you some ideas: http://wiki.python.org/moin/HowTo/Sorting/
精彩评论