Python Archive File

http://www.calazan.com/how-to-zip-an-entire-directory-with-python/

import zipfile
import sys
import os
 
def zip_folder(folder_path, output_path):
    """Zip the contents of an entire folder (with that folder included
    in the archive). Empty subfolders will be included in the archive
    as well.
    """
    parent_folder = os.path.dirname(folder_path)
    # Retrieve the paths of the folder contents.
    contents = os.walk(folder_path)
    try:
        zip_file = zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED)
        for root, folders, files in contents:
            # Include all subfolders, including empty ones.
            for folder_name in folders:
                absolute_path = os.path.join(root, folder_name)
                relative_path = absolute_path.replace(folder_path, '')
        if relative_path.startswith(os.sep):
              relative_path = relative_path[1:]            
                print "Adding '%s' as '%s' to archive." % (absolute_path, relative_path)
                zip_file.write(absolute_path, relative_path)
            for file_name in files:
                absolute_path = os.path.join(root, file_name)
                relative_path = absolute_path.replace(folder_path, '')
        if relative_path.startswith(os.sep):
              relative_path = relative_path[1:]
                print "Adding '%s' as '%s' to archive." % (absolute_path, relative_path)
                zip_file.write(absolute_path, relative_path)
        print "'%s' created successfully." % output_path
    except IOError, message:
        print message
        sys.exit(1)
    except OSError, message:
        print message
        sys.exit(1)
    except zipfile.BadZipfile, message:
        print message
        sys.exit(1)
    finally:
        zip_file.close()
 
## TEST ##
if __name__ == '__main__':
    zip_folder('/tmp/w', '/tmp/test.zip')

better approach:
https://docs.python.org/2.7/library/shutil.html

>>> import shutil
>>> shutil.make_archive('/tmp/test2', 'zip', '/tmp/w', '.')
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License