Skip to content

Instantly share code, notes, and snippets.

@Abdelkrim
Last active June 29, 2024 13:18
Show Gist options
  • Save Abdelkrim/114230349b1c661df69b1e8a9374ffd1 to your computer and use it in GitHub Desktop.
Save Abdelkrim/114230349b1c661df69b1e8a9374ffd1 to your computer and use it in GitHub Desktop.
Python script removing venv directories on Windows & Linux and, __pycahce__ directories
import os
import shutil
def is_venv_directory(path):
"""
Check if the given path is a virtual environment directory.
"""
return (
os.path.isdir(path) and
(os.path.isfile(os.path.join(path, 'bin', 'activate')) or
os.path.isfile(os.path.join(path, 'Scripts', 'activate')))
)
def is_pycache_directory(path):
"""
Check if the given path is a __pycache__ directory.
"""
return os.path.isdir(path) and os.path.basename(path) == "__pycache__"
def remove_directories(root_dir):
"""
Recursively find and remove virtual environment and __pycache__ directories.
"""
for dirpath, dirnames, filenames in os.walk(root_dir):
for dirname in dirnames:
full_dir_path = os.path.join(dirpath, dirname)
if is_venv_directory(full_dir_path):
print(f"Found venv directory: {full_dir_path}")
try:
shutil.rmtree(full_dir_path)
print(f"Deleted: {full_dir_path}")
except Exception as e:
print(f"Error deleting {full_dir_path}: {e}")
elif is_pycache_directory(full_dir_path):
print(f"Found __pycache__ directory: {full_dir_path}")
try:
shutil.rmtree(full_dir_path)
print(f"Deleted: {full_dir_path}")
except Exception as e:
print(f"Error deleting {full_dir_path}: {e}")
if __name__ == "__main__":
# Starting directory can be changed to any directory you want to start the search from
starting_directory = os.getcwd()
remove_directories(starting_directory)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment