40. File Compression

1. Compressing Files Using gzip

This example compresses a text file using the gzip module.

Copy

import gzip
import shutil

def compress_file(input_file, output_file):
    with open(input_file, 'rb') as f_in:
        with gzip.open(output_file, 'wb') as f_out:
            shutil.copyfileobj(f_in, f_out)

compress_file('example.txt', 'example.txt.gz')

This script reads the content of example.txt and writes the compressed data into example.txt.gz.


2. Extracting Files Using gzip

To decompress a .gz file, you can use the following code:

Copy

import gzip
import shutil

def decompress_file(input_file, output_file):
    with gzip.open(input_file, 'rb') as f_in:
        with open(output_file, 'wb') as f_out:
            shutil.copyfileobj(f_in, f_out)

decompress_file('example.txt.gz', 'example_decompressed.txt')

This script decompresses example.txt.gz and saves the result into example_decompressed.txt.


3. Compressing Files Using bz2

This snippet shows how to compress a file using the bz2 module.

Copy

This script compresses example.txt and writes the compressed content into example.txt.bz2.


4. Extracting Files Using bz2

To extract the content from a .bz2 file, use this code:

Copy

This decompresses example.txt.bz2 into example_decompressed.txt.


5. Creating a ZIP Archive Using zipfile

You can compress multiple files into a zip archive like this:

Copy

This script creates a archive.zip containing example.txt and example2.txt.


6. Extracting a ZIP Archive Using zipfile

To extract the contents of a ZIP file, use:

Copy

This extracts all files from archive.zip to the output_dir.


7. Listing Contents of a ZIP Archive Using zipfile

You can list the files in a ZIP archive like this:

Copy

This prints the names of the files inside archive.zip.


8. Compressing a String into a ZIP Archive Using zipfile

You can also compress data directly from a string:

Copy

This creates a ZIP archive string_archive.zip containing hello.txt with the string content "Hello, world!".


9. Compressing a Directory Using zipfile

Compress a whole directory into a ZIP file:

Copy

This will zip the entire my_folder directory into my_folder.zip.


10. Extracting Specific Files from a ZIP Archive

You can extract specific files from a ZIP archive like this:

Copy

This extracts example.txt from archive.zip to the output_dir.


These snippets demonstrate how to work with file compression and extraction using the gzip, bz2, and zipfile modules in Python. You can choose the one that best fits your use case, whether you are working with single files, directories, or even in-memory strings.

Last updated