Created
November 11, 2024 14:46
-
-
Save abdalrohman/a6ab200fef933dc0610b410d456848a3 to your computer and use it in GitHub Desktop.
Safely empty the contents of a folder while preserving the folder structure.
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 argparse | |
| from pathlib import Path | |
| from rich.console import Console | |
| from rich.progress import Progress | |
| def empty_folder(folder_path, verbose=False): | |
| folder_path = Path(folder_path) | |
| console = Console() | |
| if not folder_path.exists() or not folder_path.is_dir(): | |
| console.print(f"[red]Error: {folder_path} is not a valid directory.[/red]") | |
| return | |
| console.print(f"[yellow]Emptying folder: {folder_path}[/yellow]") | |
| with Progress() as progress: | |
| task = progress.add_task("[green]Replacing files...", total=sum(1 for _ in folder_path.rglob("*"))) | |
| for file_path in folder_path.rglob("*"): | |
| if file_path.is_file(): | |
| file_path.write_bytes(b"") | |
| if verbose: | |
| console.print(f"[blue]Replaced file: {file_path}[/blue]") | |
| progress.update(task, advance=1) | |
| console.print(f"[green]Folder {folder_path} has been emptied.[/green]") | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser( | |
| description="Safely empty the contents of a folder while preserving the folder structure." | |
| ) | |
| parser.add_argument("folder_path", help="Path to the folder to be emptied.") | |
| parser.add_argument("--verbose", "-v", action="store_true", help="Display detailed progress information.") | |
| args = parser.parse_args() | |
| console = Console() | |
| console.print( | |
| "[yellow]WARNING: This operation will replace all files in the specified folder with empty files.[/yellow]" | |
| ) | |
| console.print("[yellow]Please ensure this is the correct folder and that you want to proceed.[/yellow]") | |
| for _ in range(3): | |
| triple_prompt = console.input("[red]Type 'yes' or 'press enter' to confirm: [/red]") | |
| if triple_prompt.lower() not in ["yes", "y", ""]: | |
| console.print("[red]Operation cancelled.[/red]") | |
| exit() | |
| empty_folder(args.folder_path, args.verbose) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment