import os import zipfile import shutil import argparse from tqdm import tqdm def extract_all_zips(source_folder, destination_folder, delete_original=True): """Extract all ZIP files from the source folder to the destination folder""" # Ensure source folder exists if not os.path.exists(source_folder): print(f"Error: Source folder '{source_folder}' does not exist!") return # Ensure destination folder exists, create if not if not os.path.exists(destination_folder): os.makedirs(destination_folder) print(f"Created destination folder: {destination_folder}") # Get all ZIP files zip_files = [f for f in os.listdir(source_folder) if f.lower().endswith('.zip') and os.path.isfile(os.path.join(source_folder, f))] if not zip_files: print(f"No ZIP files found in '{source_folder}'.") return print(f"Found {len(zip_files)} ZIP files, preparing to extract...") # Extract each ZIP file for zip_file in tqdm(zip_files, desc="Extracting ZIP files"): zip_path = os.path.join(source_folder, zip_file) try: with zipfile.ZipFile(zip_path, 'r') as zip_ref: # Get list of files in the archive file_list = zip_ref.namelist() # Extract all files for file in file_list: zip_ref.extract(file, destination_folder) print(f"Successfully extracted: {zip_file}") # Delete original file if option is set if delete_original: os.remove(zip_path) print(f"Deleted original ZIP file: {zip_file}") except Exception as e: print(f"Error extracting {zip_file}: {str(e)}") print(f"\nComplete! Extracted {len(zip_files)} ZIP files to '{destination_folder}'") def compress_all_files(source_folder, destination_folder, delete_original=True): """Compress all files in source folder into separate ZIP files""" # Ensure source folder exists if not os.path.exists(source_folder): print(f"Error: Source folder '{source_folder}' does not exist!") return # Ensure destination folder exists, create if not if not os.path.exists(destination_folder): os.makedirs(destination_folder) print(f"Created destination folder: {destination_folder}") # Get all files in source folder all_files = [f for f in os.listdir(source_folder) if os.path.isfile(os.path.join(source_folder, f))] if not all_files: print(f"No files found in '{source_folder}'.") return print(f"Found {len(all_files)} files, preparing to compress...") # Compress each file for file_name in tqdm(all_files, desc="Compressing files"): source_path = os.path.join(source_folder, file_name) # Create ZIP filename (original filename + .zip) zip_file_name = file_name + ".zip" zip_path = os.path.join(destination_folder, zip_file_name) try: # Create ZIP file with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf: # Add file to ZIP using original filename within the archive zipf.write(source_path, arcname=file_name) print(f"Successfully compressed: {file_name} -> {zip_file_name}") # Delete original file if option is set if delete_original: os.remove(source_path) print(f"Deleted original file: {file_name}") except Exception as e: print(f"Error compressing {file_name}: {str(e)}") print(f"\nComplete! Compressed {len(all_files)} files to '{destination_folder}'") def compress_all_folders(source_folder, destination_folder, delete_original=True): """Compress all subfolders in source folder into separate ZIP files""" # Ensure source folder exists if not os.path.exists(source_folder): print(f"Error: Source folder '{source_folder}' does not exist!") return # Ensure destination folder exists, create if not if not os.path.exists(destination_folder): os.makedirs(destination_folder) print(f"Created destination folder: {destination_folder}") # Get all subfolders in the source folder all_folders = [f for f in os.listdir(source_folder) if os.path.isdir(os.path.join(source_folder, f))] if not all_folders: print(f"No subfolders found in '{source_folder}'.") return print(f"Found {len(all_folders)} subfolders, preparing to compress...") # Compress each subfolder for folder_name in tqdm(all_folders, desc="Compressing folders"): source_path = os.path.join(source_folder, folder_name) # Create ZIP filename zip_file_name = folder_name + ".zip" zip_path = os.path.join(destination_folder, zip_file_name) try: # Create ZIP file with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf: # Walk through all files and subfolders for root, dirs, files in os.walk(source_path): for file in files: file_path = os.path.join(root, file) # Calculate relative path to be used within the ZIP arcname = os.path.relpath(file_path, start=os.path.dirname(source_path)) zipf.write(file_path, arcname=arcname) print(f"Successfully compressed: {folder_name} -> {zip_file_name}") # Delete original folder if option is set if delete_original: shutil.rmtree(source_path) print(f"Deleted original folder: {folder_name}") except Exception as e: print(f"Error compressing {folder_name}: {str(e)}") print(f"\nComplete! Compressed {len(all_folders)} folders to '{destination_folder}'") if __name__ == "__main__": parser = argparse.ArgumentParser(description="ZIP file utility for extracting and compressing files") # Create subparsers for different commands subparsers = parser.add_subparsers(dest="command", help="Command to execute") # Extract command extract_parser = subparsers.add_parser("extract", help="Extract ZIP files") extract_parser.add_argument("--source", "-s", default="/content/UR5_DATASET/pickup_marker", help="Source folder containing ZIP files") extract_parser.add_argument("--destination", "-d", default="/content/UR5_DATASET/pickup_marker_temp/", help="Destination folder for extracted files") extract_parser.add_argument("--keep", "-k", action="store_true", help="Keep original ZIP files after extraction") # Compress command compress_parser = subparsers.add_parser("compress", help="Compress files or folders into ZIP archives") compress_parser.add_argument("--source", "-s", default="/content/UR5_DATASET/pickup_marker_temp", help="Source folder containing files or folders to compress") compress_parser.add_argument("--destination", "-d", default="/content/UR5_DATASET/pickup_marker", help="Destination folder for ZIP files") compress_parser.add_argument("--mode", "-m", choices=["files", "folders"], default="files", help="Compress individual files or entire folders") compress_parser.add_argument("--keep", "-k", action="store_true", help="Keep original files or folders after compression") args = parser.parse_args() # Execute the appropriate command if args.command == "extract": extract_all_zips(args.source, args.destination, not args.keep) elif args.command == "compress": if args.mode == "files": compress_all_files(args.source, args.destination, not args.keep) else: compress_all_folders(args.source, args.destination, not args.keep) else: parser.print_help()