Guest User

Untitled

a guest
Jan 22nd, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.41 KB | None | 0 0
  1. import os, zipfile, sys
  2.  
  3. def zip_folder(folder_path, output_path):
  4.     """Zip the contents of an entire folder (with that folder included
  5.    in the archive). Empty subfolders will be included in the archive
  6.    as well.
  7.    """
  8.     parent_folder = os.path.dirname(folder_path)
  9.     # Retrieve the paths of the folder contents.
  10.     contents = os.walk(folder_path)
  11.     try:
  12.         zip_file = zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED)
  13.         for root, folders, files in contents:
  14.             # Include all subfolders, including empty ones.
  15.             for folder_name in folders:
  16.                 absolute_path = os.path.join(root, folder_name)
  17.                 relative_path = absolute_path.replace(parent_folder + '\\',
  18.                                                       '')
  19.                 zip_file.write(absolute_path, relative_path)
  20.             for file_name in files:
  21.                 absolute_path = os.path.join(root, file_name)
  22.                 relative_path = absolute_path.replace(parent_folder + '\\',
  23.                                                       '')
  24.                 zip_file.write(absolute_path, relative_path)
  25.     except IOError, message:
  26.         print message
  27.         sys.exit(1)
  28.     except OSError, message:
  29.         print message
  30.         sys.exit(1)
  31.     except zipfile.BadZipfile, message:
  32.         print message
  33.         sys.exit(1)
  34.     finally:
  35.         zip_file.close()
Add Comment
Please, Sign In to add comment