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

利用Python的Posix接口实现文件压缩和解压缩

发布时间:2024-01-16 00:56:12

在Python中,可以使用gzip模块来实现对文件的压缩和解压缩操作。gzip模块提供了对POSIX操作系统接口的访问,可以实现对文件进行压缩和解压缩。

下面是一个使用gzip库进行文件压缩和解压缩的示例代码:

import gzip

def compress_file(file_path, compressed_file_path):
    with open(file_path, 'rb') as file:
        with gzip.open(compressed_file_path, 'wb') as compressed_file:
            compressed_file.writelines(file)

def decompress_file(compressed_file_path, decompressed_file_path):
    with gzip.open(compressed_file_path, 'rb') as compressed_file:
        with open(decompressed_file_path, 'wb') as decompressed_file:
            decompressed_file.writelines(compressed_file)

# 压缩文件
compress_file('example.txt', 'example.txt.gz')
print("文件压缩成功")

# 解压缩文件
decompress_file('example.txt.gz', 'example_decompressed.txt')
print("文件解压缩成功")

在上述代码中,compress_file函数用于对文件进行压缩,接受两个参数,file_path指定要进行压缩的文件路径,compressed_file_path指定压缩后的文件保存路径。首先,使用open函数读取文件内容,并以二进制模式读取文件内容。然后,使用gzip.open创建一个压缩文件,并将文件内容写入压缩文件中。最后,关闭文件流。

decompress_file函数用于对压缩文件进行解压缩,接受两个参数,compressed_file_path指定要进行解压缩的文件路径,decompressed_file_path指定解压缩后的文件保存路径。首先,使用gzip.open打开压缩文件,并以二进制模式读取压缩文件内容。然后,使用open函数创建一个解压缩文件,并将压缩文件内容写入解压缩文件中。最后,关闭文件流。

在使用示例代码时,可以将要压缩的文件example.txt放置在同一目录下,并确保example.txt.gzexample_decompressed.txt文件不存在。运行代码后会生成example.txt.gzexample_decompressed.txt两个文件。

请注意,gzip模块只能对单个文件进行压缩和解压缩。如果需要对目录进行压缩和解压缩,可以使用shutil模块的make_archiveunpack_archive函数。