Home  >  Article  >  Backend Development  >  How to use the gzip module for file compression and decompression in Python 2.x

How to use the gzip module for file compression and decompression in Python 2.x

WBOY
WBOYOriginal
2023-07-30 08:01:37953browse

Python is a simple and easy-to-learn programming language with a rich standard library, which includes the gzip module for file compression and decompression. This article will introduce how to use the gzip module to compress and decompress files, with code examples.

First, we need to import the gzip module:

import gzip

Next, we will introduce how to use the gzip module to compress and decompress files.

  1. File Compression

Compressing files using the gzip module is very simple. We can use the open function to open the file to be compressed and specify binary writing mode. Then, use the gzip.open function to create a file object in gzip format, passing in the file object to be compressed as a parameter. Finally, the file data is written to the gzip file object through the write method. The sample code is as follows:

def compress_file(input_filepath, output_filepath):
    with open(input_filepath, 'rb') as f_in:
        with gzip.open(output_filepath, 'wb') as f_out:
            f_out.write(f_in.read())

In the above code, input_filepath is the file path to be compressed, and output_filepath is the compressed file saving path.

  1. File decompression

It is also very simple to decompress files using the gzip module. We can use the gzip.open function to open the gzip file to be decompressed and specify binary reading mode. Then, read the gzip file data through the read method and write it to the decompressed file. The sample code is as follows:

def decompress_file(input_filepath, output_filepath):
    with gzip.open(input_filepath, 'rb') as f_in:
        with open(output_filepath, 'wb') as f_out:
            f_out.write(f_in.read())

In the above code, input_filepath is the path of the file to be decompressed, and output_filepath is the path to save the decompressed file.

The above are the basic operations of using the gzip module to compress and decompress files. With these simple code examples, we can easily implement file compression and decompression functions in Python 2.x. Hope this article is helpful to everyone!

The above is the detailed content of How to use the gzip module for file compression and decompression in Python 2.x. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn