Last active
March 14, 2025 10:49
-
-
Save jmquintana79/c59f9974889c96bf47128ff09ff3566a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import shutil | |
def clean(path:str = '.')->None: | |
""" | |
Clean files and folders generated by Python: *.pyc y __pycache__. | |
""" | |
# initialize folders to be omited | |
exclude_dirs = ["venv"] | |
# loop of paths | |
for root, dirs, files in os.walk(path): | |
# ommit folders | |
dirs[:] = [d for d in dirs if d not in exclude_dirs] | |
# loop of files | |
for file in files: | |
# remove .pyc files | |
if file.endswith(".pyc"): | |
os.remove(os.path.join(root, file)) | |
print(f"Removing: {os.path.join(root, file)}") | |
# loop of dirs | |
for dir in dirs: | |
# remove __pycache__ | |
if dir == "__pycache__": | |
shutil.rmtree(os.path.join(root, dir)) | |
print(f"Removing: {os.path.join(root, dir)}") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import shutil | |
import logging | |
def clean_files_in_dir(folder:str) -> None: | |
"""Clean files in a given directory | |
Args: | |
folder (str): Folder to be cleaned. | |
Raises: | |
ValueError: Stop | |
""" | |
# validate | |
assert os.path.exists(folder) | |
# clean folder | |
try: | |
# loop of content in a folder | |
for file in os.listdir(folder): | |
# build path | |
path = os.path.join(folder, file) | |
# if it is a file | |
if os.path.isfile(path): | |
# remove file | |
os.remove(path) | |
# if it is a folder | |
elif os.path.isdir(path): | |
# remove folder (and its content) | |
shutil.rmtree(path) | |
# display | |
logging.info(f"This folder was cleaned: '{folder}'") | |
except Exception: | |
logging.exception(f"It was not possible clean the folder '{folder}'.") | |
raise ValueError("error") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment