Skip to content

Instantly share code, notes, and snippets.

@GGLinnk
Last active May 19, 2022 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GGLinnk/3c7d00462c1ecc6a1f60cbf731f47a4c to your computer and use it in GitHub Desktop.
Save GGLinnk/3c7d00462c1ecc6a1f60cbf731f47a4c to your computer and use it in GitHub Desktop.
A python script that zips files individually and recursively from the location where it is executed or the path given as an argument.

ZIP-ALL

A python script that zips files individually and recursively from the location where it is executed or the path given as an argument.

Warning

  • THIS VERSION IS NOT TESTED! USE AT YOUR OWN RISK
  • All original files will be deleted once compressed!
  • Try to avoid running it multiple times, it does not exclude known compressed formats like other zip or rar.
  • This script uses the highest compression rate available. Note that compression can take a lot of time and power.

Instructions

Run this script in the folder whose files you want to individually and recursively compress like this:

python zip-all.py

Or you can specify the folder by running :

python zip-all.py the/path/you/want/to/recursively/zip
from pathlib import Path
import zipfile, os
from sys import argv
folder_path = argv[1] if (len(argv) > 1) else "."
file_list = list(Path(folder_path).rglob("*"))
for file_path in file_list:
zip_path = Path.joinpath(file_path.parent, file_path.stem + ".zip")
zip_file = zipfile.ZipFile(file=zip_path, mode='w', compression=zipfile.ZIP_DEFLATED, compresslevel=9)
try:
print(f"Compressing: {file_path.name} into:", zip_path)
zip_file.write(filename=file_path, arcname=file_path.name)
zip_file.close()
try:
print("Removing :", file_path)
os.remove(file_path)
print("Original file removed!")
except Exception as e:
print("Original file failed to be removed...\n", e)
print("Compression done!")
except zipfile.error as e:
zip_file.close()
print("An error occured !\n", e)
print("\nAll compression done !\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment