To accomplish your task of compressing your folder structure into ZIP files with a maximum size of 10 MB per file, while maintaining the folder structure and utilizing concurrency to speed up the process, you can use a Python script that leverages multithreading. Below is a step-by-step guide along with the script that will help you achieve this.
Prerequisites:
- Install Python 3 on your computer if you haven't already.
- Ensure you have basic knowledge of running Python scripts.
Step 1: Understand the Task
You have a directory structure like this:
C:\Users\lucas\Downloads\a\#9 Dream - John Lennon
C:\Users\lucas\Downloads\a\(Feels Like) Heaven - Fiction Factory
C:\Users\lucas\Downloads\a\(I'm Not Your) Steppin' Stone - The Monkees
...
Each song folder contains two files: other.wav and vocals.wav.
Your goal is to:
- Compress these folders into ZIP files.
- Each ZIP file should not exceed 10 MB.
- Maintain the folder structure within the ZIP files.
- Utilize concurrency to speed up the zipping process.
Step 2: The Python Script
Below is the Python script that accomplishes this task:
import os
import zipfile
from concurrent.futures import ThreadPoolExecutor
# Base directory containing the song folders
ROOT_DIR = r"C:\Users\lucas\Downloads\a"
# Maximum ZIP size in bytes (10 MB)
MAX_ZIP_SIZE = 10 * 1024 * 1024 # 10 MB in bytes
def collect_folder_sizes(root_dir):
"""Collects the sizes of each folder."""
folder_paths = [
os.path.join(root_dir, d)
for d in os.listdir(root_dir)
if os.path.isdir(os.path.join(root_dir, d))
]
folder_sizes = []
for folder_path in folder_paths:
total_size = 0
for filename in ["other.wav", "vocals.wav"]:
file_path = os.path.join(folder_path, filename)
if os.path.isfile(file_path):
total_size += os.path.getsize(file_path)
folder_sizes.append((folder_path, total_size))
return folder_sizes
def group_folders(folder_sizes, max_zip_size):
"""Groups folders into batches that do not exceed the maximum ZIP size."""
groups = []
current_group = []
current_size = 0
for folder_path, folder_size in folder_sizes:
if folder_size > max_zip_size:
# Skip folders that are too large
print(f"Folder {folder_path} exceeds maximum ZIP size and will be skipped.")
continue
if current_size + folder_size > max_zip_size:
# Start a new group
groups.append(current_group)
current_group = [folder_path]
current_size = folder_size
else:
current_group.append(folder_path)
current_size += folder_size
if current_group:
groups.append(current_group)
return groups
def zip_group(group_folders, zip_index, root_dir):
"""Zips a group of folders into a ZIP file."""
zip_filename = f'archive_{zip_index + 1}.zip'
zip_filepath = os.path.join(root_dir, zip_filename)
try:
with zipfile.ZipFile(zip_filepath, 'w', zipfile.ZIP_DEFLATED) as zipf:
for folder in group_folders:
for root, dirs, files in os.walk(folder):
for file in files:
file_path = os.path.join(root, file)
arcname = os.path.relpath(file_path, root_dir)
zipf.write(file_path, arcname)
print(f"Added {file_path} as {arcname} to {zip_filename}")
print(f"Created {zip_filename}")
except Exception as e:
print(f"Error creating {zip_filename}: {e}")
def main():
folder_sizes = collect_folder_sizes(ROOT_DIR)
groups = group_folders(folder_sizes, MAX_ZIP_SIZE)
# Use ThreadPoolExecutor to zip groups concurrently
with ThreadPoolExecutor(max_workers=4) as executor:
futures = []
for i, group in enumerate(groups):
future = executor.submit(zip_group, group, i, ROOT_DIR)
futures.append(future)
# Wait for all tasks to complete
for future in futures:
future.result()
print("All archives have been created.")
if __name__ == "__main__":
main()
Step 3: How the Script Works
-
Collect Folder Sizes:
- The script starts by collecting all the song folders within the root directory.
- It calculates the total size of the
other.wav and vocals.wav files in each folder.
-
Group Folders:
- It groups the folders into batches where the total size does not exceed 10 MB.
- Folders that individually exceed 10 MB are skipped (you can modify this behavior if needed).
-
Zip Groups Concurrently:
- The script uses
ThreadPoolExecutor from the concurrent.futures module to zip multiple groups at the same time.
- Each group is processed by the
zip_group function, which creates a ZIP file containing all folders in that group while maintaining the folder structure.
-
Maintain Folder Structure:
- When adding files to the ZIP archive,
arcname (the name of the file within the archive) is set using os.path.relpath, which ensures the relative path is preserved.
-
Concurrency:
- The
max_workers=4 parameter allows up to 4 groups to be zipped simultaneously. You can adjust this number based on your system's capabilities.
Step 4: Running the Script
-
Save the Script:
- Copy the script into a text editor and save it with a
.py extension, e.g., compress_music.py.
-
Adjust the ROOT_DIR:
-
Ensure the ROOT_DIR in the script matches the root directory of your music folders.
ROOT_DIR = r"C:\Users\lucas\Downloads\a"
-
The r before the string denotes a raw string, which helps handle backslashes in Windows paths.
-
Run the Script:
-
Open a command prompt or terminal window.
-
Navigate to the directory where you saved the script.
-
Run the script with Python:
python compress_music.py
-
Monitor Output:
-
The script will print messages indicating which files are being added to which ZIP archives.
-
Upon completion, you should see the message:
All archives have been created.
-
Check the Output:
- The ZIP files (
archive_1.zip, archive_2.zip, etc.) will be created in the ROOT_DIR.
- Each ZIP file will contain the grouped folders with the maintained directory structure.
Notes and Considerations
Conclusion
By using this script, you can efficiently compress your music folders into ZIP files of up to 10 MB each while maintaining the folder structure. The use of concurrency with ThreadPoolExecutor helps speed up the process by handling multiple ZIP operations simultaneously.
If you have any questions or need further assistance with customizing the script to fit your specific needs, feel free to ask!