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 :

os.listdir(path)

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 :

first.txt
second.md
third.mp3

I have also created one file example.py with the below code :

import os

print(os.listdir())

It prints the contents of the folder including itself :

['third.mp3', 'example.py', 'first.txt', 'second.md']

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

print(sorted(os.listdir()))

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

['example.py', 'first.txt', 'second.md', 'third.mp3']

Similar tutorials :