import os | |
import tarfile | |
import shutil | |
from tqdm import tqdm | |
def create_tar_and_remove_dir(dirname, tar_name): | |
# Check if the directory exists | |
if not os.path.isdir(dirname): | |
print("The specified directory does not exist.") | |
return | |
# Create the tar file | |
with tarfile.open(tar_name, "w") as tar: | |
# Sort and add files to the tar file | |
for root, dirs, files in os.walk(dirname): | |
# Sort files for consistent ordering | |
for file in tqdm(sorted(files), desc="Creating tars..."): | |
full_path = os.path.join(root, file) | |
# Add the file to the tar archive | |
tar.add(full_path, arcname=os.path.relpath(full_path, dirname)) | |
# Remove the original directory after archiving | |
# shutil.rmtree(dirname) | |
print(f"The directory {dirname} has been removed.") | |
# Example usage of the function | |
# Replace 'your_directory_name' with the actual directory name you want to tar and remove | |
create_tar_and_remove_dir("danbooru2/0202", f"danbooru-tars/0202.tar") | |