78. Zip Compression with zipfile

Here are Python code examples for compressing and decompressing files using the zipfile module:

1. Compressing Files into a ZIP Archive

This example shows how to compress multiple files into a single .zip file.

import zipfile

def compress_files(zip_filename, file_list):
    with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
        for file in file_list:
            zipf.write(file)
            print(f"Compressed {file}")

# Example usage
files_to_compress = ['file1.txt', 'file2.txt', 'image.jpg']
compress_files('archive.zip', files_to_compress)

2. Adding Files to an Existing ZIP Archive

You can append files to an existing .zip file instead of overwriting it.

import zipfile

def append_to_zip(zip_filename, file_list):
    with zipfile.ZipFile(zip_filename, 'a', zipfile.ZIP_DEFLATED) as zipf:
        for file in file_list:
            zipf.write(file)
            print(f"Added {file} to the archive")

# Example usage
files_to_add = ['new_file.txt']
append_to_zip('archive.zip', files_to_add)

3. Extracting All Files from a ZIP Archive

This example demonstrates how to extract all files from a .zip archive to a specific directory.


4. Extracting Specific Files from a ZIP Archive

If you only want to extract specific files from a .zip archive, you can use the extract() method.


5. Listing the Contents of a ZIP Archive

You can list all the files inside a .zip archive without extracting them.


6. Compressing a Directory into a ZIP Archive

To compress an entire directory into a .zip file, you need to walk through the directory and add each file individually.


7. Creating a Password-Protected ZIP Archive

Although the zipfile module doesn't natively support password protection, this example uses a workaround by using the pyzipper module, which supports encrypted .zip files.

(Note: You need to install pyzipper using pip install pyzipper to use this functionality.)


8. Reading File Information in a ZIP Archive

You can read file metadata (like size, date) from a .zip file without extracting them.


9. Extracting Files from a ZIP Archive Using Password

If the .zip file is encrypted, you can extract files by providing the password.


10. Check if File Exists in ZIP Archive

You can check whether a specific file exists in a .zip archive before extracting it.


These snippets demonstrate various ways to work with .zip files in Python, from simple compression and extraction to advanced use cases like password protection and handling encrypted archives.

Last updated