Python压缩&解压缩

本文详细介绍了Python中常用的压缩模块:zipfile、tarfile和gzip的使用方法。包括如何使用这些模块进行文件的压缩和解压缩操作,适用于各种场景的数据打包和解包需求。

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值