Sort
files, sizeWhich are the smallest and largest files in a directory? With the "os" module, we can list the files and get their sizes with getsize.
In Python, we can use a list of tuples to store the file paths along with their sizes in bytes. Then a separate sort()
call can perform the required reordering.
This program creates a list of 2-item tuples. Each tuple contains a file name and its size. It then sorts the list based on the size item of the tuples. It first imports the "os" module.
sort()
with a lambda that sorts based on a key. The key is the first element (the size) of each tuple.import os # 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) pairs.append((size, file)) # Step 5: sort list of tuples by the first element, size. pairs.sort(key=lambda s: s[0]) for pair in pairs: print(pair)(184, 'file.pl') (235, 'file.php') (369, 'file.rb') (611, 'file.py')
In the resulting list, the files are sorted from smallest to largest. The list can be reversed with the reverse()
method.
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.