Skip to content

Instantly share code, notes, and snippets.

@hmidani-abdelilah
Created May 16, 2025 10:09
Show Gist options
  • Save hmidani-abdelilah/c3928678a72ae75e5d0a9ad951877994 to your computer and use it in GitHub Desktop.
Save hmidani-abdelilah/c3928678a72ae75e5d0a9ad951877994 to your computer and use it in GitHub Desktop.
import os
import shutil
import py7zr
import argparse
import sys
def compress_with_py7zr_and_remove(folder_path, archive_name):
folder_path = os.path.abspath(folder_path)
if not os.path.isdir(folder_path):
print("❌ The folder does not exist!")
sys.exit(1)
parent_dir = os.path.dirname(folder_path)
archive_path = os.path.join(parent_dir, archive_name + ".7z")
try:
print(f"πŸ”„ Compressing folder: {folder_path}")
with py7zr.SevenZipFile(archive_path, 'w') as archive:
archive.writeall(folder_path, arcname=os.path.basename(folder_path))
print(f"βœ… Folder successfully compressed to: {archive_path}")
shutil.rmtree(folder_path)
print(f"πŸ—‘οΈ Original folder has been deleted: {folder_path}")
except Exception as e:
print(f"❌ Compression failed: {e}")
sys.exit(1)
def main():
parser = argparse.ArgumentParser(description="πŸ“¦ Compress a folder into a .7z archive and delete the original.")
parser.add_argument("folder", help="Path to the folder to compress")
parser.add_argument("name", help="Name of the output archive (without .7z)")
args = parser.parse_args()
compress_with_py7zr_and_remove(args.folder, args.name)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment