Created
August 23, 2023 06:41
-
-
Save EtaoinWu/4f56dd4ea14df000b5161fe40ac3efe9 to your computer and use it in GitHub Desktop.
Recursively remove files older than 1mo and remove empty directories. Useful for QQ group photos cleanup. Co-written by ChatGPT.
This file contains 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 time | |
import pathlib | |
from tqdm import tqdm | |
def is_file_old(file_path, month_in_seconds = 30*24*60*60): | |
"""Returns if the file is not a directory and is at least one month old.""" | |
if os.path.isdir(file_path): | |
return False | |
file_time = os.path.getmtime(file_path) | |
return (time.time() - file_time) >= month_in_seconds | |
def is_directory_empty(dir_path): | |
"""Returns if the directory is empty.""" | |
if not os.path.isdir(dir_path): | |
return False | |
return not any(True for _ in pathlib.Path(dir_path).iterdir()) | |
# Define directory path. | |
dir_path = '.' # replace with your directory | |
# List files recursively | |
all_files = [x for x in tqdm(pathlib.Path(dir_path).rglob('*.*'))] | |
# Initialize progress bar | |
pbar = tqdm(total=len(all_files), desc="Processing files") | |
for file in all_files: | |
if is_file_old(file): | |
os.remove(file) | |
pbar.update(1) | |
pbar.close() | |
all_dirs = [x for x in tqdm(pathlib.Path(dir_path).rglob('*'))] | |
pbar_dirs = tqdm(total=len(all_dirs), desc="Processing directories") | |
# Remove empty directories | |
for dir_ in reversed(all_dirs): # reverse to go from the deepest directory | |
if is_directory_empty(dir_): | |
os.rmdir(dir_) | |
pbar_dirs.update(1) | |
pbar_dirs.close() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment