Press "Enter" to skip to content

Python – List All Files in a Directory and Sub-Directory

Here is an example of a Python program to list all files in a directory and sub-directory.

List Files in a Directory and Sub-Directory Using Python OS.WALK

In the below example, it will list all the files in a directory (F:\Python\Python37) and sub-directory.

import os


def traverse(path):
    for basepath, directories, files in os.walk(path):
        for f in files:
            yield os.path.join(basepath, f)

for f in traverse('F:\Python\Python37'):
    print(f)

Output

F:\Python\Python37\LICENSE.txt
F:\Python\Python37\NEWS.txt
F:\Python\Python37\python.exe
F:\Python\Python37\python3.dll
F:\Python\Python37\python37.dll
F:\Python\Python37\pythonw.exe
F:\Python\Python37\vcruntime140.dll
F:\Python\Python37\cx_Oracle-doc\LICENSE.txt
F:\Python\Python37\cx_Oracle-doc\README.txt
F:\Python\Python37\DLLs\libcrypto-1_1-x64.dll
F:\Python\Python37\DLLs\libssl-1_1-x64.dll
F:\Python\Python37\DLLs\py.ico
F:\Python\Python37\DLLs\pyc.ico
F:\Python\Python37\DLLs\pyd.ico
F:\Python\Python37\DLLs\pyexpat.pyd
F:\Python\Python37\DLLs\python_lib.cat
F:\Python\Python37\DLLs\python_tools.cat
F:\Python\Python37\DLLs\select.pyd
F:\Python\Python37\DLLs\sqlite3.dll
F:\Python\Python37\DLLs\tcl86t.dll
...