Skip to content

Get list of files in directory sorted by names using os.listdir()

This snippet fetches the list of files in a directory sorting them by their names using os.listdir(). Earlier we used glob() to do this.

import os
dir_name = '/home/Documents/'
# Get list of all files in a given directory sorted by name
list_of_files = sorted( filter( lambda x: os.path.isfile(os.path.join(dir_name, x)),
                        os.listdir(dir_name) ) )
for file_name in list_of_files:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.