![]() |
In this article, we will be looking at the different approaches to get the list of the files in the given directory in the sorted order of size in the Python programming language. The two different approaches to get the list of files in a directory are sorted by size is as follows:
Method 1: Using os.listdir() functionos.listdir() method in Python is used to get the list of all files and directories in the specified directory. If we don’t specify any directory, then a list of files and directories in the current working directory will be returned.
In this method, we will create a list of filenames in a folder sorted by file size. We will pass lambda x: os.stat(os.path.join(dir_name, x)).st_size as the key argument to the sorted() function which will sort the files in directory by size. Python3
Output: 366 --> descript.ion 1688 --> readme.txt 3990 --> License.txt 15360 --> Uninstall.exe 48844 --> History.txt 50688 --> 7-zip32.dll 78336 --> 7-zip.dll 108074 --> 7-zip.chm 186880 --> 7zCon.sfx 205824 --> 7z.sfx 468992 --> 7z.exe 581632 --> 7zG.exe 867840 --> 7zFM.exe 1679360 --> 7z.dll Method 2: Using glob() functionIn python programming language we have the glob module which provides a function called glob() which is used to find files or directories in a given directory based on the matching pattern. Using the glob() function we can use wildcards and regular expression to match and find few files in a directory or all files in a directory. In this method, we will use glob() function to get a list of all files in a directory along with the size. The steps are as follows, First, we will get list of all files in a directory using glob(), then we will sort the list of files based on the size of files using sorted() function. We will use os.stat(file_path).st_size to fetch the file size from stat object of file. Then we will pass the encapsulated size in a lambda function as the key argument in the sorted() function. Python3
Output: 366 --> C:/Program Files/7-Zip\descript.ion 1688 --> C:/Program Files/7-Zip\readme.txt 3990 --> C:/Program Files/7-Zip\License.txt 15360 --> C:/Program Files/7-Zip\Uninstall.exe 48844 --> C:/Program Files/7-Zip\History.txt 50688 --> C:/Program Files/7-Zip\7-zip32.dll 78336 --> C:/Program Files/7-Zip\7-zip.dll 108074 --> C:/Program Files/7-Zip\7-zip.chm 186880 --> C:/Program Files/7-Zip\7zCon.sfx 205824 --> C:/Program Files/7-Zip\7z.sfx 468992 --> C:/Program Files/7-Zip\7z.exe 581632 --> C:/Program Files/7-Zip\7zG.exe 867840 --> C:/Program Files/7-Zip\7zFM.exe 1679360 --> C:/Program Files/7-Zip\7z.dll |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 9 |