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.

Copy

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.

Copy


3. Extracting All Files from a ZIP Archive

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

Copy


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.

Copy


5. Listing the Contents of a ZIP Archive

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

Copy


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.

Copy


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.

Copy

(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.

Copy


9. Extracting Files from a ZIP Archive Using Password

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

Copy


10. Check if File Exists in ZIP Archive

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

Copy


Last updated