File size: 8,301 Bytes
c27ccc6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 | 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() |