Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get files from Directory Argument, Sorting by Size

Tags:

python

I'm trying to write a program that takes a command line argument, scans through the directory tree provided by the argument and creating a list of every file in the directory, and then sorting by length of files.

I'm not much of a script-guy - but this is what I've got and it's not working:

import sys
import os
from os.path import getsize

file_list = []

#Get dirpath
dirpath = os.path.abspath(sys.argv[0])
if os.path.isdir(dirpath):
    #Get all entries in the directory
    for root, dirs, files in os.walk(dirpath):
        for name in files:
            file_list.append(name)
        file_list = sorted(file_list, key=getsize)
        for item in file_list:
            sys.stdout.write(str(file) + '\n')

else:
    print "not found"

Can anyone point me in the right direction?

like image 983
wadda_wadda Avatar asked Nov 27 '13 20:11

wadda_wadda


1 Answers

Hopefully this function will help you out (I'm using Python 2.7):

import os    

def get_files_by_file_size(dirname, reverse=False):
    """ Return list of file paths in directory sorted by file size """

    # Get list of files
    filepaths = []
    for basename in os.listdir(dirname):
        filename = os.path.join(dirname, basename)
        if os.path.isfile(filename):
            filepaths.append(filename)

    # Re-populate list with filename, size tuples
    for i in xrange(len(filepaths)):
        filepaths[i] = (filepaths[i], os.path.getsize(filepaths[i]))

    # Sort list by file size
    # If reverse=True sort from largest to smallest
    # If reverse=False sort from smallest to largest
    filepaths.sort(key=lambda filename: filename[1], reverse=reverse)

    # Re-populate list with just filenames
    for i in xrange(len(filepaths)):
        filepaths[i] = filepaths[i][0]

    return filepaths
like image 67
J. Owens Avatar answered Oct 06 '22 00:10

J. Owens