0
0
PythonHow-ToBeginner · 3 min read

Find All Python Files in Directory Recursively in Python

Use Python's pathlib.Path.rglob() method to search recursively for all files ending with .py in a directory. This method returns an iterator of all matching files in the directory and its subfolders.
📐

Syntax

The main syntax to find all Python files recursively is:

  • Path('directory_path').rglob('*.py'): Searches for all files ending with .py inside the given directory and all its subdirectories.
  • Path: Represents a filesystem path.
  • rglob(pattern): Recursively matches files using the given pattern.
python
from pathlib import Path

# Syntax pattern
directory = Path('your_directory_path')
python_files = directory.rglob('*.py')
💻

Example

This example shows how to print all Python files in the current directory and its subdirectories.

python
from pathlib import Path

# Use current directory
current_dir = Path('.')

# Find all .py files recursively
for py_file in current_dir.rglob('*.py'):
    print(py_file)
Output
./script1.py ./folder/script2.py ./folder/subfolder/script3.py
⚠️

Common Pitfalls

Common mistakes when searching for Python files recursively include:

  • Using glob() instead of rglob(), which only searches the top directory, missing files in subfolders.
  • Not converting the path to a string if needed for other operations.
  • Assuming the search is case-insensitive; on some systems, *.py will not match .PY files.
python
from pathlib import Path

# Wrong: only searches top directory
files_wrong = list(Path('.').glob('*.py'))

# Right: searches recursively
files_right = list(Path('.').rglob('*.py'))
📊

Quick Reference

Tips for finding Python files recursively:

  • Use rglob('*.py') for recursive search.
  • Use Path('your_path') to specify the directory.
  • Iterate over the result to access each file.
  • Remember rglob includes all subdirectories.

Key Takeaways

Use pathlib.Path.rglob('*.py') to find all Python files recursively.
rglob searches the directory and all its subdirectories.
Avoid glob() if you want to include subfolders in the search.
Iterate over the rglob result to process each Python file.
Be aware of case sensitivity depending on your operating system.