[Tutor] Re: get_size(n,directory,files)

Isr Gish isrgish at fusemail.com
Mon Feb 16 10:13:10 EST 2004


Christropher,

I was wondering, that when you add each file to your dictonary files_of_size{}. If there would be 2 files with same size you would only get the second one in the dict. 

This may be a rare thing, but in that why start with a dict then maKe a list of it.

I think you should use a list to begin with.

biggest_files = [(f, os.path.getsize(f)) for f in files]

Then the whole function can be written like this.

def get_size(n,directory,files):

#Creates a list of tuples (filepathname, size). (or you could change this '('  to '[' and ')' to ']' for a list).
    files = [os.path.join(directory, f) for f in files]
    biggest_files = [(f, os.path.getsize(f)) for f in files if not os.path.isdir(f) and not os.path.islink(f)]
    biggest_files.sort(lambda f1, f2: cmp(f2[1], f1[1]))


    print "in directory %s:" % directory

    try:
        while n > 0:
            print biggest_files[n-1]
            n -= 1
    except IndexError, msg:
            print "%d is too high.  Try a smaller number" %n

#Prints out the n largest files.


All the best,
Isr




More information about the Tutor mailing list