在Python中,有多种库可以用于文件压缩和解压
示例代码:
import gzip
# 压缩文件
with open('file.txt', 'rb') as src, gzip.open('file.gz', 'wb') as dst:
dst.writelines(src)
# 解压缩文件
with gzip.open('file.gz', 'rb') as src, open('file.txt', 'wb') as dst:
dst.writelines(src)
示例代码:
import bz2
# 压缩文件
with open('file.txt', 'rb') as src, bz2.open('file.bz2', 'wb') as dst:
dst.writelines(src)
# 解压缩文件
with bz2.open('file.bz2', 'rb') as src, open('file.txt', 'wb') as dst:
dst.writelines(src)
示例代码:
import lzma
# 压缩文件
with open('file.txt', 'rb') as src, lzma.open('file.lzma', 'wb') as dst:
dst.writelines(src)
# 解压缩文件
with lzma.open('file.lzma', 'rb') as src, open('file.txt', 'wb') as dst:
dst.writelines(src)
示例代码:
import zipfile
# 压缩文件
with zipfile.ZipFile('file.zip', 'w', compression=zipfile.ZIP_DEFLATED) as zf:
zf.write('file.txt')
# 解压缩文件
with zipfile.ZipFile('file.zip', 'r') as zf:
zf.extractall()
示例代码:
import tarfile
# 创建TAR文件
with tarfile.open('file.tar', 'w') as tf:
tf.add('file.txt')
# 解压TAR文件
with tarfile.open('file.tar', 'r') as tf:
tf.extractall()
这些库提供了高效的压缩和解压算法,可以根据实际需求选择合适的库进行文件压缩和解压。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。