[zipfile] Python packages files as zip packages & decompresses them

Using Python to compress files, you can use the zipfile library, which provides a very rich API
zipfile itself is a context manager, and you can use with . The following is a simple demo.

pack

import os
import zipfile


def file2zip(zip_file_name: str, file_names: list):
    """ Compress and store files in multiple folders as zip
    
    :param zip_file_name: /root/Document/test.zip
    :param file_names: ['/root/user/doc/test.txt', ...]
    :return: 
    """
    # Read-write mode ZipFile requires mode 'r', 'w', 'x', or 'a'
    # Compression mode ZIP_STORED: stored; ZIP_DEFLATED: compressed storage
    with zipfile.ZipFile(zip_file_name, mode='w', compression=zipfile.ZIP_DEFLATED) as zf:
        for fn in file_names:
            parent_path, name = os.path.split(fn)
            
            # zipfile built-in provides for storing files compressed in .zip files, arcname is the name of the file stored in the zip file
            # The given archive name is arcname (by default it will be the same as filename, but without the drive letter and will remove the opening path separator)
            zf.write(fn, arcname=name)
            
            # Equivalent to the following two lines of code
            # Switch directories to write the file directly. Without switching directories, the entire path to the file is created in the zip file
            # os.chdir(parent_path)
            # zf.write(name)


if __name__ == "__main__":
	zip_name = '/root/Document/test.zip'
	files = ['/root/user/doc/test.txt', '/root/user/doc/test1.txt']
	file2zip(zip_name , files)

decompression

def zip2file(zip_file_name: str, extract_path: str, members=None, pwd=None):
    """ Folder specified by the zip file content extraction value

    :param zip_file_name: the file to be extracted .zip r'D:\Desktop\tst\tst.zip'
    :param extract_path: the directory where the extracted file is saved r'D:\Desktop\tst\test\test'
    :param members: specify the files to extract, default all
    :param pwd: the password to extract the file
    :return:
    """
    with zipfile.ZipFile(zip_file_name) as zf:
        zf.extractall(extract_path, members=members, pwd=pwd)

Python file compression

zipfile. Pyzipfile inherits from zipfile. Zipfile , and has a special writepy to package . Py . PyC


Read More: