Nesse diretório /home/paperspace/karaoke-version-dataset tem 62496 pastas e em cada pasta tem vários arquivos MP3.
E o tamanho total desse diretório é de 164 GB
Preciso de um script python que cria 4 arquivos ZIP que não dependa do outro com o tamanho que não exceda 40 GB.
Assistant
Sure, I can help you with that. Here's a Python script that will create multiple ZIP files from your dataset directory, ensuring that each ZIP file does not exceed 40 GB in size. Given the total size of your dataset is 164 GB, the script will create as many ZIP files as needed to accommodate all the data without exceeding the size limit per ZIP file.
python
import os
import math
import zipfile
def create_zip_archives(base_dir, zip_size_limit_gb=40, output_dir=None):
# Set the size limit per ZIP file (in bytes)
zip_size_limit = zip_size_limit_gb * 1024 * 1024 * 1024 # Convert GB to bytes
if output_dir is None:
output_dir = base_dir # Use base directory if output directory not specified
files_info = []
# Collect all files and their sizes
for root, dirs, files in os.walk(base_dir):
for file in files:
full_path = os.path.join(root, file)
if os.path.isfile(full_path): # Ensure it's a file
size = os.path.getsize(full_path)
files_info.append({'path': full_path, 'size': size})
total_size = sum(f['size'] for f in files_info)
num_bins = math.ceil(total_size / zip_size_limit)
# Warn the user if the number of ZIP files exceeds 4
if num_bins > 4:
print(f"Warning: Total dataset size is {total_size/(1024**3):.2f} GB, which requires {num_bins} ZIP files to stay under {zip_size_limit_gb} GB per ZIP file.")
# Initialize bins for files
bins = [{'files': [], 'size': 0} for _ in range(num_bins)]
# Sort files by size in descending order
files_info.sort(key=lambda x: x['size'], reverse=True)
# Distribute files into bins
for f in files_info:
placed = False
# Try to place the file into a bin without exceeding the size limit
for b in bins:
if b['size'] + f['size'] <= zip_size_limit:
b['files'].append(f['path'])
b['size'] += f['size']
placed = True
break
if not placed:
# If the file doesn't fit in any bin, create a new bin
new_bin = {'files': [f['path']], 'size': f['size']}
bins.append(new_bin)
num_bins += 1
print(f"Added an extra ZIP file to accommodate file {f['path']}.")
# Create ZIP files
for idx, b in enumerate(bins):
zip_filename = os.path.join(output_dir, f"karaoke_archive_part{idx+1}.zip")
print(f"Creating {zip_filename} with {len(b['files'])} files, total size: {b['size']/(1024**3):.2f} GB.")
with zipfile.ZipFile(zip_filename, 'w', compression=zipfile.ZIP_STORED, allowZip64=True) as zf:
for file_path in b['files']:
# Add file to ZIP with a relative path
arcname = os.path.relpath(file_path, start=base_dir)
zf.write(file_path, arcname=arcname)
print("ZIP file creation complete.")
# Example usage:
if __name__ == "__main__":
base_directory = '/home/paperspace/karaoke-version-dataset'
create_zip_archives(base_directory)
Explanation:
Collecting Files: The script walks through the given directory, collecting all file paths and their sizes.
Calculating Number of ZIP Files: It calculates the total size of all files and determines the number of ZIP files needed based on the 40 GB limit.
Distributing Files into ZIPs: It sorts the files by size (largest first) and assigns them to the ZIP files (bins) without exceeding the size limit per ZIP.
Handling Oversized Files: If a file is too large to fit into any existing ZIP file without exceeding the size limit, it creates a new ZIP file for that file.
Creating ZIP Files: It creates the ZIP files, adding the files to each ZIP using relative paths for consistency.
Compression: The script uses ZIP_STORED to store files without additional compression since MP3 files are already compressed. This also speeds up the zipping process.
Allowing ZIP64: The allowZip64=True parameter ensures that the script can create ZIP files larger than 4 GB, which is necessary for large datasets.
Note:
The script may create more than 4 ZIP files if necessary to ensure no ZIP file exceeds 40 GB.
Make sure you have sufficient disk space for the output ZIP files.
The script uses relative paths inside the ZIP files to preserve the directory structure.
How to Run the Script:
Save the script to a file, for example create_zip_archives.py.
Ensure you have Python 3 installed on your system.
Run the script from the command line:
bash
python3 create_zip_archives.py
You can also specify a different directory or output directory by modifying the base_directory variable or passing arguments.
Please test the script with a smaller subset of your data first to ensure it works as expected before processing the entire dataset.