Reputation: 33
The following gets the files, but they are not sorted.
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))
Upvotes: 3
Views: 8855
Reputation: 71
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)
Upvotes: 7
Reputation: 4495
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)
Upvotes: 1
Reputation: 1
Maybe this will give you some ideas: http://wiki.python.org/moin/HowTo/Sorting/
Upvotes: 0
Reputation: 25609
A way
>>> import operator
>>> import os
>>> getall = [ [files, os.path.getsize(files)] for files in os.listdir(".") ]
>>> sorted(getall, key=operator.itemgetter(1))
Upvotes: 11