Get files from Directory Argument, Sorting by Size
python
Solution
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
Problem
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?