Computer >> Computer tutorials >  >> Programming >> Python

How to list down all the files alphabetically using Python?


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']