Recursively list all python files under a directory

From raju

Python script

Use the following script to list all the python files in a directory and any of the sub directories there in.

    $cat list_python_files.py
    #! /usr/bin/env python
    
    # Recursively list all python files under a directory
    import os
    import sys
    
    if (len(sys.argv) < 2):
        path = '.'
    else:
        path = sys.argv[1]
    
    files = [os.path.join(root, file)
             for root, dirs, files in os.walk(path)
             for file in files
             if file.endswith('.py')]
    # print("python files under ", path)
    print(*files, sep='\n')
    

Sample usage

Using the following directory structure

    raju@DESKTOP-PAOP7BQ MINGW64 ~/work/shoutwiki
    $ls -R
    .:
    basic_math/  list_python_files.py*
    
    ./basic_math:
    addition.py*
    

Running the script

    raju@DESKTOP-PAOP7BQ MINGW64 ~/work/shoutwiki
    $./list_python_files.py
    .\list_python_files.py
    .\basic_math\addition.py
    
    raju@DESKTOP-PAOP7BQ MINGW64 ~/work/shoutwiki
    $./list_python_files.py basic_math/
    basic_math/addition.py
    
    raju@DESKTOP-PAOP7BQ MINGW64 ~/work/shoutwiki
    $cd basic_math/
    
    raju@DESKTOP-PAOP7BQ MINGW64 ~/work/shoutwiki/basic_math
    $../list_python_files.py
    .\addition.py
    
    raju@DESKTOP-PAOP7BQ MINGW64 ~/work/shoutwiki/basic_math
    $../list_python_files.py ..
    ..\list_python_files.py
    ..\basic_math\addition.py
    
    raju@DESKTOP-PAOP7BQ MINGW64 ~/work/shoutwiki/basic_math
    $../list_python_files.py ~/work/shoutwiki/
    C:/Users/raju/work/shoutwiki/list_python_files.py
    C:/Users/raju/work/shoutwiki/basic_math\addition.py
    

Related links