How to Remove __pycache__
Folders and .pyc
Files in Python
When you run Python scripts, the interpreter often creates bytecode cache files (.pyc
) stored in __pycache__
directories. These caches help speed up subsequent module loading. While generally harmless, you might want to remove them to clean up your project directory, reduce clutter in version control, or ensure a completely fresh execution environment.
This guide provides several methods using shell commands (find
, xargs
, rm
) and Python itself to effectively remove __pycache__
directories and .pyc
/.pyo
files from your project.
Understanding __pycache__
and .pyc
Files
.pyc
Files: When Python imports a module (.py
file) for the first time, it compiles the source code into a lower-level representation called bytecode and saves it as a.pyc
file. Running the.pyc
file directly is faster on subsequent imports because the compilation step is skipped.__pycache__
Directories: Since Python 3.2, these.pyc
files are stored in subdirectories named__pycache__
within the directory containing the original.py
file. This keeps the main directory cleaner. (.pyo
files are similar but relate to optimized bytecode, less common now).
These cache files are usually managed automatically by Python, but cleaning them manually can sometimes be useful.
Method 1: Using find
and rm
(Linux/macOS)
The find
command is powerful for locating files and directories based on criteria, and rm
removes them. Run these commands from your project's root directory in the terminal.
Combined find
Command (Recommended)
This command finds files named *.pyc
or *.pyo
or directories named __pycache__
and deletes them.
# Find files ending in .pyc or .pyo AND delete them,
# OR find directories named __pycache__ AND delete them (and their contents).
find . -type f -name '*.py[co]' -delete -o -type d -name __pycache__ -delete
find .
: Search starting from the current directory (.
).-type f
: Find items that are files.-name '*.py[co]'
: Match filenames ending in.pyc
or.pyo
.[co]
matches 'c' or 'o'.-delete
: Delete the found files.-o
: Acts as an OR operator.-type d
: Find items that are directories.-name __pycache__
: Match directories named exactly__pycache__
.-delete
: Delete the found directories (this works for directories in many modernfind
versions; if not, use the-exec
method below).
Separate find
Commands
You can achieve the same with separate commands:
# 1. Find and delete all .pyc/.pyo files recursively
find . -type f -name '*.py[co]' -delete
# 2. Find and delete all __pycache__ directories recursively
# Using -exec rm -rf {} + is robust if -delete doesn't work for dirs
find . -type d -name __pycache__ -exec rm -rf {} +
-exec rm -rf {} +
: Executes therm -rf
command on the found directories ({}
). The+
groups multiple finds into fewerrm
calls for efficiency.
Using find
with -regex
(Alternative)
This uses regular expressions to match the desired paths.
# Find paths matching the regex and delete them
find . -regex '^.*\(/__pycache__\|\.py[co]\)$' -delete
-regex '...'
: Matches the entire path against the regular expression.^.*
: Matches the beginning of the path and any characters.(/__pycache__\|\.py[co]\)
: Matches either a directory ending in/__pycache__
OR (\|
) a file ending in.pyc
or.pyo
. The backslashes escape the parentheses and pipe for the regex engine.$
: Matches the end of the path.
Method 2: Using Command Prompt/PowerShell (Windows)
Windows requires different commands. Run these from your project's root directory.
Deleting .pyc
/.pyo
Files
In Batch Script:
:: Command Prompt
:: /s searches recursively, /q runs quietly
del /s /q *.pyc
del /s /q *.pyo
In PowerShell:
# PowerShell
Get-ChildItem -Recurse -Include *.pyc, *.pyo | Remove-Item -Force
Deleting __pycache__
Folders
In Batch Script
:: Command Prompt
:: /s searches recursively, /q runs quietly
for /d /r . %d in (__pycache__) do @if exist "%d" rd /s /q "%d"
In PowerShell:
# PowerShell
Get-ChildItem -Recurse -Directory -Filter __pycache__ | Remove-Item -Recurse -Force
Method 3: Using Python (pathlib
) (Cross-Platform)
You can write a small Python script using the pathlib
module to find and remove these files/directories. This approach works on any OS where Python runs.
# clean_cache.py
import pathlib
import shutil
import os
current_dir = pathlib.Path('.') # Start in the current directory
print("Deleting .pyc/.pyo files...")
for path in current_dir.rglob('*.py[co]'): # Find all matching files recursively
try:
path.unlink() # Delete file
print(f" Deleted file: {path}")
except OSError as e:
print(f" Error deleting file {path}: {e}")
print("Deleting __pycache__ directories...")
for path in current_dir.rglob('__pycache__'): # Find all matching dirs recursively
if path.is_dir(): # Double check it's a directory
try:
# Use shutil.rmtree to remove directory and its contents
shutil.rmtree(path)
print(f" Deleted directory: {path}")
except OSError as e:
print(f" Error deleting directory {path}: {e}")
print("Cleanup complete.")
Save this as clean_cache.py
in your project root and run it using python clean_cache.py
.
pathlib.Path('.')
: Represents the current directory..rglob('*.py[co]')
: Recursively finds files matching the pattern.path.unlink()
: Deletes a file..rglob('__pycache__')
: Recursively finds items named__pycache__
.shutil.rmtree(path)
: Deletes a directory and all its contents.
Method 4: Using pyclean
(Debian/Ubuntu Tool)**
On Debian-based systems like Ubuntu, the pyclean
tool (often installed via sudo apt install python3-minimal
) can remove bytecode files.
# Run from your project root directory
py3clean .
This tool specifically targets bytecode files associated with the system's Python installations.
Creating a Reusable Shell Alias/Function (Linux/macOS)
If you need to clean cache frequently, add a function or alias to your shell configuration file (~/.bashrc
, ~/.zshrc
, ~/.bash_profile
).
- Edit your profile file: (e.g.,
nano ~/.bashrc
) - Add the function:
# Function to remove Python cache files/dirs
rmpycache() {
echo "Removing __pycache__ directories and .pyc/.pyo files..."
find . -type f -name '*.py[co]' -delete -o -type d -name __pycache__ -delete
echo "Done."
} - Save and close the editor.
- Reload the profile:
source ~/.bashrc
(or your specific file). - Use the command: Navigate to your project root and simply run
rmpycache
.
Preventing __pycache__
Creation (Environment Variables)
PYTHONDONTWRITEBYTECODE
: If this environment variable is set to a non-empty string (e.g.,export PYTHONDONTWRITEBYTECODE=1
), Python will completely stop generating.pyc
files. This can slow down imports slightly.PYTHONPYCACHEPREFIX
(Python 3.8+): Set this environment variable to a path (e.g.,export PYTHONPYCACHEPREFIX="$HOME/.cache/pycache"
). Python will write.pyc
files to a parallel directory structure under that path instead of creating__pycache__
folders within your project source tree. The target directory must exist.
Setting these variables can keep your source directories clean but might impact import performance or require managing the central cache location.
Conclusion
Removing Python bytecode cache (__pycache__
, .pyc
, .pyo
) is straightforward using various tools:
- Linux/macOS: The
find
command offers powerful one-liners (e.g.,find . -type f -name '*.py[co]' -delete -o -type d -name __pycache__ -delete
). Create a shell function for easy reuse. - Windows: Use
del
for files and afor /d
loop for directories in Command Prompt, orGet-ChildItem | Remove-Item
in PowerShell. - Cross-Platform: A Python script using
pathlib
provides a reliable OS-independent solution. - Debian/Ubuntu: The
py3clean .
command is a dedicated tool.
Choose the method most convenient for your operating system and workflow. Consider using environment variables like PYTHONPYCACHEPREFIX
if you want to avoid creating __pycache__
directories within your projects altogether.