How to sort all files in a folder in Python

Sorting all files in a folder while reading :

Python os module provides us listdir function to list all files in a directory or folder. We need to pass the directory path to this function and it returns us the name of all entries in that folder. This function is defined as below :


The returned list of the files is in arbitary order. It also doesn’t include any special entries . and .. even if it is included. The path parameter is optional starting from python 3.2. If you don’t pass the path, it will return all entries in the current folder.

Example :

For this example, I have created one folder with three files :


I have also created one file with the below code :

import os


It prints the contents of the folder including itself :

['third.mp3', '', 'first.txt', '']

These names are not sorted. If you want to sort the names, you need to use the sorted function with result like below :

import os


Execute it and it will print all files sorted by name :

['', 'first.txt', '', 'third.mp3']

Similar tutorials :