# Step 1: get all files.
directory = "programs/"
list = os.listdir(directory)
# Step 2: loop and add files to list.
pairs = 
for file in list:
# Step 3: Use join to get full file path.
location = os.path.join(directory, file)
# Step 4: get size and add to list of tuples.
size = os.path.getsize(location)
# Step 5: sort list of tuples by the first element, size.
pairs.sort(key=lambda s: s)
for pair in pairs:
Results. In the resulting list, the files are sorted from smallest to largest. The list can be reversed with the reverse() method.
And This code could be used to determine the largest files in a directory, which might need to be deleted first.
Summary. Sorting can be simple, but often elements must be sorted in an associative way. A list of tuples is ideal for this—a lambda expression can select the item to sort upon.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.