Python压缩&解压缩

Python中常用的压缩模块有zipfile、tarfile、gzip

1.zipfile模块的简单使用

import zipfile

# 压缩
z1 = zipfile.ZipFile('zip_test', 'w')
z1.write('src')
z1.write('dst4')
z1.close()

# 解压缩
with zipfile.ZipFile('zip_test', 'r') as z2:
    print(z2.read('src').decode())  # 查看压缩包中src文件内容
    z2.extractall('zip123')         # 解压文件到zip123目录下

2.tarfile模块的简单使用

import tarfile

# 压缩
t1 = tarfile.TarFile('tar_test', 'w')
t1.add('src', 'dst2')
t1.close()

# 解压缩
with tarfile.TarFile('tar_test') as t2:
    t2.extractall('tar123')     # 解压文件到tar123目录下

3.gzip模块的简单使用

import gzip

f = open('src', encoding='utf-8').read()
f = f.encode(encoding='utf-8')
print(type(f))

with gzip.GzipFile('gzip_test', 'w') as g1:
    g1.write(f)

with gzip.GzipFile('gzip_test') as g2:
    print(g2.read().decode())
    print(type(g2))

原文地址:https://www.cnblogs.com/Caiyundo/p/9444022.html