mhs
mhs

Reputation: 33

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] == '.':
            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

Answers (4)

Gil Hiller-Mizrahi
Gil Hiller-Mizrahi

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

Raisen
Raisen

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

Garot
Garot

Reputation: 1

Maybe this will give you some ideas: http://wiki.python.org/moin/HowTo/Sorting/

Upvotes: 0

kurumi
kurumi

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

Related Questions