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 :
- List all the files in a Zip file using Python 3
- Python program to sort words of a string in alphabetical order
- Python program to sort values of one list using second list
- Python program to merge two lists and sort it
- Python program to delete all files with specific extension in a folder
- Python program to remove special characters from all files in a folder