TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to PYTHON

Python Sort by File Size

Sort a list of files in a directory by their sizes. Use the os.listdir method.
Sort files, size. A directory contains files of many sizes. Which are the smallest and largest files? With the "os" module, we can list the files and get their sizes with getsize. We use a list of tuples.
Example. This program, from a high level, creates a list of two-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.

Listdir: The program uses the listdir method, part of the "os" module. The file names include no directories.

Path

Join: It next uses the join method. This method combines the directory with the file name.

Getsize: It finally uses the getsize method. This returns the size. It adds a new tuple to the pairs list.

Finally: We call the sort method with an argument, a lambda expression that sorts based on a key. The key is the first element (the size) of each tuple.

SortLambda
Python program that sorts files by size import os # The folder containing files. directory = "C:\\programs\\" # Get all files. list = os.listdir(directory) # Loop and add files to list. pairs = [] for file in list: # Use join to get full file path. location = os.path.join(directory, file) # Get size and add to list of tuples. size = os.path.getsize(location) pairs.append((size, file)) # Sort list of tuples by the first element, size. pairs.sort(key=lambda s: s[0]) # Display pairs. for pair in pairs: print(pair) Output (184, 'file.pl') (235, 'file.php') (369, 'file.rb') (611, 'file.py')
In the resulting list, the files are sorted from smallest to largest. All the script files in my directory were small, between 184 bytes to 611 bytes. The list can be reversed with the reverse() method.
Summary. Sorting can be simple, as shown on many websites, or complex. 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.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf