Python executable to Linux list files with sizes
Question: I need my test.py to display the following in LINUX shell \- list all files in
directory \- descending order of file size in bytes (must display bytes) \-
show total files and total size at end (X files X total size) \- does not
include sub directories or files in other subdirectories

here is my python executable

    
    
        #!/usr/bin/env python
        import subprocess
        subprocess.call(["ls", "-l", "-S", "-s"])
    

this shows me the files and their size in descending order but it includes
folders/subdirectories which I do not want

additionally replacing the subprocess.call with subprocess.call(["find",
"-type","f"]) shows me only the files without the unneeded dates and times but
I don't know how to get the info I want.

My python code:

    
    
    #!/usr/bin/env python 
    import subprocess, os, operator 
    directory='e:\\Programs/Cyg/home/Dylan/test'       
    list=os.listdir(directory) 
    pairs=[] 
    for file in list:
        if os.path.isfile: 
            location=os.path.join(directory, file)   
            size=os.path.getsize(location) pairs.append((file,size))  
    pairs.sort(key=operator.itemgetter(0)) 
    for pair in pairs:
       print (pair)
    


Answer: ## Current directory

    
    
    from os import listdir
    from os.path import isfile, getsize
    from operator import itemgetter
    
    files = [(f, getsize(f)) for f in listdir('.') if isfile(f)]
    files.sort(key=itemgetter(1), reverse=True)
    
    for f, size in files:
        print '%d %s' % (size, f)
    print '(%d files %d total size)' % (len(files), sum(f[1] for f in files))
    

## Other directories

    
    
    from os import listdir
    from operator import itemgetter
    from os.path import isfile, getsize, join, basename
    
    def listfiles(dir):
        paths = (join(dir, f) for f in listdir(dir))
        files = [(basename(p), getsize(p)) for p in paths if isfile(p)] 
        files.sort(key=itemgetter(1), reverse=True)
    
        for f, size in files:
            print '%d %s' % (size, f)
        print '(%d files %d total size)' % (len(files), sum(f[1] for f in files))
    

