How do I list all files of a directory in Python?

PythonServer Side ProgrammingProgramming

os.listdir(my_path) will get you everything that's in the my_path directory - files and directories.

Example

You can use it as follows:

>>> import os
>>> os.listdir('.')
['DLLs', 'Doc', 'etc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'pythonw.exe', 'README.txt', 'Scripts', 'share', 'tcl', 'Tools', 'w9xpopen.exe']

Output

If you want just files, you can filter it using isfile:

>>> import os
>>> file_list = [f for f in os.listdir('.') if os.path.isfile(os.path.join('.', f))]
>>> print file_list
['LICENSE.txt', 'NEWS.txt', 'python.exe', 'pythonw.exe', 'README.txt', 'w9xpopen.exe']
raja
Published on 26-Dec-2017 11:18:28
Advertisements