How to use os.listdir() function In Python

os.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.

Syntax: os.listdir(path)

Parameters: path (optional) : path of the directory

Return: This method returns the list of all files and directories in the specified path. The return type of this method is list.

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




import os
  
name_of_dir = 'dir_path'
  
# Storing list of all files
# in the given directory in list_of_files
list_of_files = filter( lambda x: os.path.isfile
                       (os.path.join(name_of_dir, x)),
                        os.listdir(dir_name) )
  
# Sort list of file names by size 
list_of_files = sorted( list_of_files,
                        key =  lambda x: os.stat
                       (os.path.join(name_of_dir, x)).st_size)
  
# Iterate over sorted list of file 
# names and print them along with size one by one 
for name_of_file in list_of_files:
    path_of_file = os.path.join(name_of_dir, name_of_file)
    size_of_file  = os.stat(path_of_file).st_size 
    print(size_of_file, ' -->', name_of_file)


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

Python – Get list of files in directory sorted by size

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:

Similar Reads

Method 1: Using os.listdir() function

os.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....

Method 2: Using glob() function

...