欢迎访问宙启技术站
智能推送

在Python中学习gzip压缩和解压缩技术

发布时间:2023-12-11 06:50:56

gzip是一种常见的文件压缩和解压缩技术,可以有效地减小文件的大小。在Python中,我们可以使用gzip模块对文件进行压缩和解压缩操作。

下面是一个使用gzip压缩和解压缩技术的示例:

1. 压缩文件

import gzip

def compress_file(filename):
    with open(filename, 'rb') as f_in:
        with gzip.open(filename + '.gz', 'wb') as f_out:
            f_out.writelines(f_in)
    print(f'压缩文件 {filename} 完成。')

compress_file('example.txt')

上述代码中,我们通过使用gzip.open函数创建一个压缩文件的写入流,然后将源文件的内容逐行写入压缩文件。

2. 解压文件

import gzip

def decompress_file(filename):
    with gzip.open(filename, 'rb') as f_in:
        with open(filename[:-3], 'wb') as f_out:
            f_out.writelines(f_in)
    print(f'解压缩文件 {filename} 完成。')

decompress_file('example.txt.gz')

上述代码中,我们通过使用gzip.open函数创建一个解压缩文件的读取流,然后将压缩文件的内容逐行写入目标文件。

3. 压缩字符串

import gzip

def compress_string(string):
    data = bytes(string, 'utf-8')
    with gzip.open('compressed_string.gz', 'wb') as f_out:
        f_out.write(data)
    print(f'压缩字符串完成。')

compress_string('Hello, World!')

上述代码中,我们将字符串转换为字节流,并使用gzip.open函数创建一个压缩文件的写入流,然后将字节流写入压缩文件。

4. 解压字符串

import gzip

def decompress_string(filename):
    with gzip.open(filename, 'rb') as f_in:
        data = f_in.read()
    string = data.decode('utf-8')
    print(f'解压缩字符串完成:{string}')

decompress_string('compressed_string.gz')

上述代码中,我们首先使用gzip.open函数创建一个解压缩文件的读取流,然后读取全部内容,并将字节流转换为字符串。

以上就是使用gzip压缩和解压缩技术的示例。你可以根据具体的需求进行相应的调整和扩展。压缩和解压缩能够帮助我们降低文件的大小并节省存储空间,同时在文件传输过程中也能提高传输效率。