How do you get a directory listing sorted by their name in Python?

PythonServer Side ProgrammingProgramming

You can call the os.listdir function to get the list of the directory contents and use the sorted function to sort this list.

For example

>>> import os
>>> list_dir = os.listdir('.')
>>> list_dir = [f.lower() for f in list_dir]   # Convert to lower case
>>> sorted(list_dir)
['dlls', 'doc', 'etc', 'include', 'lib', 'libs', 'license.txt', 'news.txt', 'python.exe', 'pythonw.exe', 'readme.txt', 'scripts', 'share', 'tcl', 'tools', 'w9xpopen.exe']
raja
Published on 27-Dec-2017 10:17:40
Advertisements